Key-Value Coding Programming Guide 閱讀筆記

KVC

需要遵從協(xié)議 NSKeyValueCoding , NSObject 遵從此協(xié)議,實(shí)現(xiàn)協(xié)議方法,所以大多數(shù) NSObject 的子類不必重寫這兩個(gè)方法:

- (id)valueForKey:(NSString *)key;
- (void)setValue:(nullable id)value forKey:(NSString *)key;
  • valueForKey: 取定義過的key值
    特別的是,在容器類上調(diào)用此方法,會(huì)將消息傳遞給容器類中的每一個(gè)對象,而不是對容器本身進(jìn)行操作。
  • valueForUndefinedKey: 取未定義的key值
    未重寫此方法時(shí),易導(dǎo)致NSUnknownKeyException錯(cuò)誤

key 與 keyPath 的區(qū)別

A key is a string that identifies a specific property.

A key path is a string of dot-separated keys used to specify a sequence of object properties to traverse.

給基本類型的屬性置 nil,程序會(huì)崩潰引發(fā) NSInvalidArgumentException 異常。

重寫- (void)setNilValueForKey:(NSString *)key 方法避免異常。

A collection operator is one of a small list of keywords preceded by an at sign (@) that specifies an operation that the getter should perform to manipulate the data in some way before returning it.

Search Pattern for the Basic Getter

對于setValue:屬性值 forKey:@"name";代碼,底層的執(zhí)行機(jī)制如下:

(1).程序優(yōu)先調(diào)用“setName:屬性值;”代碼通過setter方法完成設(shè)置。

(2).如果該類沒有setName:方法,KVC機(jī)制會(huì)搜索該類名為name的成員變量,找到后對name成員變量賦值。

(3).如果該類既沒有setName:方法,也沒有定義_name成員變量,KVC機(jī)制會(huì)搜索該類名為name的成員變量,找到后對name成員變量賦值。

(4).如果上面3條都沒有找到,系統(tǒng)將會(huì)執(zhí)行該對象的setValue: forUndefinedKey:方法。默認(rèn)setValue: forUndefinedKey:方法會(huì)引發(fā)一個(gè)異常,將會(huì)導(dǎo)致程序崩潰。

對于“valueForKey:@"name";”代碼,底層執(zhí)行機(jī)制如下:

(1).程序優(yōu)先調(diào)用"name;"代碼來獲取該getter方法的返回值。

(2).如果該類沒有name方法,KVC機(jī)制會(huì)搜索該類名為name的成員變量,找到后返回name成員變量的值。

(3).如果該類既沒有name方法,也沒有定義_name成員變量,KVC機(jī)制會(huì)搜索該類名為name的成員變量,找到后返回name成員變量的值。

(4).如果上面3條都沒有找到,系統(tǒng)將會(huì)執(zhí)行該對象的valueForUndefinedKey:方法。默認(rèn)valueForUndefinedKey:方法會(huì)引發(fā)一個(gè)異常,將會(huì)導(dǎo)致程序崩潰。

Adopting Key-Value Coding

Using a @propertystatement, allowing the compiler to automatically synthesize the ivar and accessors.

@property 自動(dòng)為屬性配置get、set方法

Normally, the compiler does this for you when automatically synthesizing properties, but if you use an explicit @synthesize directive, you can enforce this naming yourself:

@synthesize 為屬性配置名字

@synthesize title = _title;

use a @dynamic directive to inform the compiler that you will provide getters and setters at runtime.

@dynamic 為屬性動(dòng)態(tài)提供get、set方法

When the property is a scalar or a structure, the default implementation of key-value coding wraps the value in an object for use on the protocol method’s interface

參考文章:
iOS 之鍵值編碼(KVC)與鍵值監(jiān)聽(KVO)

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

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

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