OC学习那些事:@property和@synthesize

1.@property 

只用在.h文件中@interface关键字中 

当编译器遇见@property时,会自动展开成getter和setter方法的声明 

//等效 
@property int age; 
 
-(int)age; 
-(void)setAge:(int)newAge; 

注意:在XCode4.5环境下,检测到@property时,自动在.m文件中添加@synthesize age = _age。如.h文件,没有声明_age变量,则自动在.m文件中添加私有的成员变量_age 

2.@synthesize 

只用在.m文件中的@implements关键字 

当编译器遇见@synthesize时,会自动展开成getter和setter方法的实现,默认访问同名的成员变量 

@synthesize age = _age;代表get方法和set方法会访问_age这个成员变量 

//等效 
@synthesize age = _age; 
 
-(void)setAge:(int)newAge 
{ 
    _age = newAge; 
} 
 
-(int)age 
{ 
    return _age; 
}  

注意:如果没有找到成员变量,自动生成私有同名成员变量 

3.完整的使用 

Person.h文件 

@interface Person:NSObject 
{ 
    int _ID; 
    float _weight; 
} 
@property int ID; 
@property float weight; 
 
@end 

Person.m文件 

@implement Person 
 
@synthesize ID = _ID; 
@synthesize weight = _weight; 
 
@end 

4.综合使用 

以上@property和@synthesize关键字和getter/setter方法可以混合使用 

如果在某种特殊的需求下,手动实现了getter/setter方法时,则@synthesize无效 

Person.h文件 

@interface Person:NSObject 
{ 
    int _ID; 
    float _weight; 
} 
@property int ID; 
@property float weight; 
 
@end 

Person.m文件 

@implement Person 
 
-(void)setID:int newID 
{ 
    //在getter/setter方法中,有特殊的操作 
    _ID = newID *100; 
} 
 
    -(int)ID 
{ 
    return _ID; 
} 
@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值