當你定義了一系列的變量時,需要寫很多的getter和setter方法,而且它們的形式都是差不多的,,所以Xcode提供了@property和@synthesize屬性,@property用在 .h 頭文件中用作聲明,@synthesize用在.m 文件中用於實現。
如下,新建一個基於“command Line Tool”的項目,名為“property”,再新建一個Student類,
傳統的寫法是:
Student.h
- //
- // Student.h
- // property
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface Student : NSObject
- {
- int age;
- int no;
- }
- //age的getter和setter方法聲明
- - (int)age;
- - (void)setAge:(int)newAge;
- //no的getter和setter方法聲明
- - (int)no;
- - (void)setNo:(int)newNo;
- @end
Student.m
- //
- // Student.m
- // property
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import "Student.h"
- @implementation Student
- //age的getter和setter方法的實現
- - (int)age
- {
- return age;
- }
- -(void)setAge:(int)newAge
- {
- age = newAge;
- }
- //no的getter和setter方法的實現
- - (int)no
- {
- return no;
- }
- - (void)setNo:(int)newNo
- {
- no = newNo;
- }
- @end
main.m
- //
- // main.m
- // property
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #import "Student.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- // insert code here...
- Student *stu = [[Student alloc] init];
- stu.age = 100;//這句相當於setter方法
- NSLog(@"age is %i", stu.age);//這裏的 stu.age 相當於getter方法
- [stu release];
- }
- return 0;
- }
用@property和@synthesize的寫法是:
Student.h
[cpp] view plain copy print ?- //
- // Student.h
- // property
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- @interface Student : NSObject
- {
- int age;
- int no;
- }
- //當編譯器遇到@property時,會自動展開成getter和setter的聲明
- @property int age;
- @property int no;
- @end
Student.m [cpp] view plain copy print ?
- //
- // Student.m
- // property
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import "Student.h"
- @implementation Student
- //@synthesize 會自動生成getter和setter的實現
- //@synthesize 默認會去訪問age,no,height同名的變量,,
- //如果找不到同名的變量,會在內部自動生成一個私有同名變量age,no,height,,
- //因此Student.h 中的這幾個變量也可以省略不寫。
- @synthesize age,no;
- @end
main.m [cpp] view plain copy print ?
- //
- // main.m
- // property
- //
- // Created by Rio.King on 13-8-25.
- // Copyright (c) 2013年 Rio.King. All rights reserved.
- //
- #import <Foundation/Foundation.h>
- #import "Student.h"
- int main(int argc, const char * argv[])
- {
- @autoreleasepool {
- // insert code here...
- Student *stu = [[Student alloc] init];
- stu.age = 100;
- NSLog(@"age is %i", stu.age);
- [stu release];
- }
- return 0;
- }
幾點說明:
1.在Xcode4.5及以後的版本中,可以省略@synthesize ,編譯器會自動幫你加上getter 和 setter 方法的實現,並且默認會去訪問
_age這個成員變量,如果找不到_age這個成員變量,會自動生成一個叫做 _age的私有成員變量。
2.視頻教學中建議變量名用"_"前綴作為開頭,但我看big Nerd 那本書裏是不用的,個人也比較習慣 big Nerd 的那種寫法,所以變量名就不加前綴了。Y^o^Y
Tags: Copyright interface property import 而且
文章來源: