Person.h
- #ifndef oc_Person_h
- #define oc_Person_h
- @interface Person : NSObject
- {
- int age;
- @protected
- float height;
- }
- - (int) age; //get方法
- - (void) setAge:(int)pAge; //set方法
- @end
- #endif
Person.m
- #import <Foundation/Foundation.h>
- #import "Person.h"
- @implementation Person
- - (int) age
- {
- return age;
- }
- - (void) setAge:(int)pAge
- {
- age = pAge;
- }
- @end
main.m
- int main()
- {
- Person* per = [[Person alloc] init];
- int age = [per age]; //调用get方法
- [per setAge:16]; //调用set方法
- //使用“.” 来调用get/set 使用的都是原始变量名,这就要求变量的get、set都符合约定
- int age2 = per.age; //get
- per.age = 17; //set
- return 0;
- }
每次这样写get/set方法,很麻烦,OC有一个自动化的方法,即使用 @proterty 和 @synthesize 关键字
Person.h
- #ifndef oc_Person_h
- #define oc_Person_h
- @interface Person : NSObject
- {
- int age;
- @protected
- // float height;
- }
- //- (int) age;
- //- (void) setAge:(int)pAge;
- @property int age; //编译器自动解释成 int age的get/set方法 的声明。
- //@property int age = _age;//如果没有指定成员变量名,实现中默认访问的同名的成员变量age
- @property float height; //如果height没有声明,而用在这里, 也会自动生成以height为标准名的 get/set方法
- @end
- #endif
Person.m
- #import <Foundation/Foundation.h>
- #import "Person.h"
- @implementation Person
- //- (int) age
- //{
- // return age;
- //}
- //
- //- (void) setAge:(int)pAge
- //{
- // age = pAge;
- //}
- @synthesize age; //编译器自动解释成 age的get、set方法实现。 在xcode4.5之后可以不写这句话
- @synthesize height = _height; //如果_height不存在,会生成一个私有的_height变量
- @end