oc中成员变量的set/get方法 以及 属性点语法的使用

来源:互联网 发布:耳机返听软件 编辑:程序博客网 时间:2024/04/29 21:26

Person.h

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #ifndef oc_Person_h  
  2. #define oc_Person_h  
  3.   
  4. @interface Person : NSObject  
  5. {  
  6.     int age;  
  7. @protected  
  8.     float height;  
  9. }  
  10. - (int) age; //get方法  
  11. - (void) setAge:(int)pAge;  //set方法  
  12.   
  13. @end  
  14.   
  15. #endif  

Person.m

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #import <Foundation/Foundation.h>  
  2. #import "Person.h"  
  3. @implementation Person  
  4.   
  5. - (int) age  
  6. {  
  7.     return age;  
  8. }  
  9.   
  10. - (void) setAge:(int)pAge  
  11. {  
  12.     age = pAge;  
  13. }  
  14.   
  15. @end  

main.m

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. int main()  
  2. {  
  3.     Person* per = [[Person alloc] init];  
  4.     int age = [per age]; //调用get方法  
  5.     [per setAge:16]; //调用set方法  
  6.       
  7.     //使用“.” 来调用get/set  使用的都是原始变量名,这就要求变量的get、set都符合约定  
  8.     int age2 = per.age//get  
  9.     per.age = 17//set  
  10.       
  11.     return 0;  
  12. }  

每次这样写get/set方法,很麻烦,OC有一个自动化的方法,即使用@proterty@synthesize关键字

Person.h

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #ifndef oc_Person_h  
  2. #define oc_Person_h  
  3.   
  4. @interface Person : NSObject  
  5. {  
  6.     int age;  
  7. @protected  
  8.   //  float height;  
  9. }  
  10. //- (int) age;  
  11. //- (void) setAge:(int)pAge;  
  12.   
  13. @property int age; //编译器自动解释成 int age的get/set方法 的声明。  
  14. //@property int age = _age;//如果没有指定成员变量名,实现中默认访问的同名的成员变量age  
  15. @property float height;  //如果height没有声明,而用在这里, 也会自动生成以height为标准名的 get/set方法  
  16. @end  
  17.   
  18. #endif  

Person.m

[objc] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. #import <Foundation/Foundation.h>  
  2. #import "Person.h"  
  3. @implementation Person  
  4.   
  5. //- (int) age  
  6. //{  
  7. //    return age;  
  8. //}  
  9. //  
  10. //- (void) setAge:(int)pAge  
  11. //{  
  12. //    age = pAge;  
  13. //}  
  14. @synthesize age; //编译器自动解释成 age的get、set方法实现。  在xcode4.5之后可以不写这句话  
  15. @synthesize height = _height; //如果_height不存在,会生成一个私有的_height变量  
  16. @end  
0 0
原创粉丝点击