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

——- 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值