oc當中通過@property和 @synthesize 配對使用來自動生成變量的set和get方法,通過使用點語法可以大大減少我們程序員代碼量,也方便學習過其他語言的人上手oc語言
@property有以下幾種屬性
readwrite 默認
assign 默認
readonly 只讀(只有get方法,禁用set方法)
給setter和getter方法起別名(setter = a:, getter = b)
atomic 開啟多線程變量保護,會消耗一定的資源(非原子性,保證多線程安全)
nonatomic:禁止多線程變量保護,提高性能
assign:直接賦值,適用於基本數據類型(非對象類型)
retain:賦值時做內存優化,使用於對象類型
copy:復制一個副本,適用於特殊的對象類型(常用於NSstring)(有NSCoping協議的才可以用copy)
assign retain copy的setter方法的內部實現
assign:
@property float price;
內部實現:
- (void)setPrice:(float)price
{
_price = price;
}
getter是:
- (float)price
{
return _price;
}
retain:
@property (retain, nonatomic) NSString *company;
內部實現:
- (void)setCompany:(NSString *)company{
if(_company != company){
[_company release];
[company retain];
_company = company;
}
}
copy:
@property (copy, readwrite, nonatomic) NSString *company;
內部實現:
- (void) setCompany:(NSString *)company{
if(_company != company){
[_company release];
[company copy];
_company = company;
}
}