黑马程序员——OC-Setter/Getter函数及@proterty和@synthesize

来源:互联网 发布:中国历史延续 知乎 编辑:程序博客网 时间:2024/04/30 08:57

——- android培训、java培训、期待与您交流! ———-

Setter函数

setter函数,对成员变量赋值。Set函数的一般写法以对age操作为例,写法为:

-(void)setName:(NNString*)name;    //声明setter函数

Get函数

getter函数,对成员变量取值。Get函数的一般写法也以对age的操作为例,写法为:

-(int)age;                  //声明getter函数

具体实现如下例子:

Person.h

@interface Person : NSObject  {      int age;  @protected      float height;  }  - (int) age;                   //get方法  - (void) setAge:(int)pAge;      //set方法  @end  

Person.m

#import <Foundation/Foundation.h>  #import "Person.h"  @implementation Person  - (int) age  {      return age;  }  - (void) setAge:(int)pAge  {      age = pAge;  }  @end  

main.m

#import <Foundation/Foundation.h>#import "Person.h"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;  }  

@proterty和@synthesize

每次这样写get/set方法,很麻烦,OC有一个自动化的方法,即使用@proterty和@synthesize关键字可以自动完成getter/setter方法的声明及实现。

具体如下所示:

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  

Person.m

#import <Foundation/Foundation.h>  #import "Person.h"  @implementation Person  @synthesize age; //编译器自动解释成 age的get、set方法实现。  在xcode4.5之后可以不写这句话  @synthesize height = _height; //如果_height不存在,会生成一个私有的_height变量  @end  

@proterty的增强

Person.h

@interface Person : NSObject  {      int age;  @protected    //  float height;  }  //- (int) age;  //- (void) setAge:(int)pAge;  @property int age; //编译器自动解释成 int age的get/set方法 的声明以及实现。    @property float height;  //如果height没有声明,而用在这里, 也会自动生成以height为标准名的 get/set方法 并 将其实现@end  

Person.m

#import <Foundation/Foundation.h>  #import "Person.h"  @implementation Person  //  @proterty增强的功能已经将getter/setter方法实现,不需要自己手动编写@end  
0 0
原创粉丝点击