關(guān)于iOS屬性修飾詞的一些事情(1)

iOS屬性修飾詞有非常多,網(wǎng)上的資料也是一抓一大把,就不一一闡述了。

這里主要講的是屬性下劃線 _ 與成員變量的聯(lián)系 、readOnly修飾符。

先上代碼:

@interface Person : NSObject

{

?// ?NSString *_age;

}

@property(nonatomic,strong) NSString *age;

@property(nonatomic,strong,readonly) NSString *name;

@end


1.屬性下劃線 _ 與成員變量的聯(lián)系

我們之所以能在.m文件中可以直接的使用_age實(shí)例變量,原因就在于蘋(píng)果將默認(rèn)編譯器從GCC轉(zhuǎn)換為L(zhǎng)LVM,從此不再需要為屬性聲明實(shí)例變量了。如果LLVM發(fā)現(xiàn)一個(gè)沒(méi)有匹配實(shí)例變量的屬性,它將自動(dòng)創(chuàng)建一個(gè)以下劃線開(kāi)頭的實(shí)例變量也就是_age。


2.由readOnly修飾符引發(fā)的一些思考:

用readOnly修飾符,系統(tǒng)不會(huì)自動(dòng)生成setter方法。

思考一:如果外部要修改屬性值的話(huà),可以通過(guò)什么方式去修改?

答案是用KVC去修改

Person *model = [[Person alloc] init];

NSLog(@"Person name:%@",model.name);

[model setValue:@"Mr right" forKey:@"name"];

NSLog(@"Person name:%@",model.name);

輸出:

2017-03-26 13:24:50.017421 [922:296049] Person name:(null)

2017-03-26 13:24:50.017522 [922:296049] Person name:Mr right


思考二:怎么防止外部去修改readOnly的屬性值?

重寫(xiě)+ (BOOL)accessInstanceVariablesDirectly;

官方文檔解釋?zhuān)篊ontrols whether the NSKeyValueCoding methods may attempt to access instance variables directly. NSObject's implementation returns YES.

控制是否NSKeyValueCoding方法可以直接訪問(wèn)實(shí)例變量。NSObject的實(shí)現(xiàn)返回的是。

Person *model = [[Person alloc] init];

NSLog(@"Person name:%@,age:%@",model.name,model.age);

[model setValue:@"18" forKey:@"age"];

NSLog(@"Person age:%@",model.age);

[model setValue:@"Mr right" forKey:@"name"];

NSLog(@"Person name:%@",model.name);


輸出:

2017-03-26 13:38:41.981745 [941:299100] Person name:(null),age:(null)

2017-03-26 13:38:41.981796 [941:299100] Person age:18

[model setValue:@"18" forKey:@"age"];可以正常賦值。

程序走到 [model setValue:@"Mr right" forKey:@"name"]; 會(huì)報(bào)錯(cuò)。


至此,本文章結(jié)束。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容