一、設置器setter 訪問器getter
setter:
set+首字母大寫的實例變量名
如:- (void)setNickName:(NSString *) name;//參數名不要與實例變量名相同
getter:
與實例變量名相同(沒有短橫線),並且返回值類型也一致
例:
@interface Cup:NSObject
{
float _price;
}
- (void)setPrice:(float)price;
- (float)price;
@end
二、屬性和實例變量的區別
1. oc中實例變量的訪問方式
oc中成員變量有三種訪問權限,@public,@protected,@private。默認是@protected,再C++中默認是private。
@public 直接使用‘->’
@private @protected都需要分別給出設置方法和訪問方法
建議實例變量都加下划線,與系統命名方式一致
2.property 屬性是一組設置器和訪問器,需要聲明和實現
@property float price;
@synthesize price = _price;
(方法調試出錯要會看 [receiver message])
3.屬性的屬性
屬性也可以設置屬性(attribute):讀寫(readonly,默認是readwrite)屬性,原子性屬性,setter語義屬性
(1)readonly 只讀
(2)給setter和getter方法起別名(setter = a:, getter = b)
atomic 開啟多線程變量保護,會消耗一定的資源(非原子性,保證多線程安全)
nonatomic:禁止多線程變量保護,提高性能
(3)setter語義屬性:
assign:直接賦值,適用於基本數據類型(非對象類型)
retain:賦值時做內存優化,使用於對象類型
copy:復制一個副本,適用於特殊的對象類型(有NSCoping協議的才可以用copy)
assign retain copy的setter方法的內部實現(筆試題)
assign:
@property float price;
內部實現:
- (void)setPrice:(float)price
{
_price = price;
}
getter是:
- (float)price
{
return _price;
}
retain:
@property (retain, readwrite, 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;
}
}
三、使用屬性和點語法
點語法(和[receriver message]是等價的)
1.性能有點差,內部轉化為setter,getter
2.不易理解蘋果的調用機制
3.屬性
只要有setter(或getter)就可以使用點語法
四、封裝
封裝的好處:
使用起來更加簡單
變量更加安全
可以隱藏內部實現細節
開發速度加快