KVC
需要遵從協(xié)議 NSKeyValueCoding , NSObject 遵從此協(xié)議妇斤,實現(xiàn)協(xié)議方法株依,所以大多數(shù) NSObject 的子類不必重寫這兩個方法:
- (id)valueForKey:(NSString *)key;
- (void)setValue:(nullable id)value forKey:(NSString *)key;
- valueForKey: 取定義過的key值
特別的是膘螟,在容器類上調(diào)用此方法吴趴,會將消息傳遞給容器類中的每一個對象尿招,而不是對容器本身進(jìn)行操作。 - valueForUndefinedKey: 取未定義的key值
未重寫此方法時登淘,易導(dǎo)致NSUnknownKeyException錯誤
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浪读,程序會崩潰引發(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ī)制會搜索該類名為name的成員變量方面,找到后對name成員變量賦值放钦。
(3).如果該類既沒有setName:方法,也沒有定義_name成員變量恭金,KVC機(jī)制會搜索該類名為name的成員變量操禀,找到后對name成員變量賦值。
(4).如果上面3條都沒有找到横腿,系統(tǒng)將會執(zhí)行該對象的setValue: forUndefinedKey:方法颓屑。默認(rèn)setValue: forUndefinedKey:方法會引發(fā)一個異常,將會導(dǎo)致程序崩潰耿焊。
對于“valueForKey:@"name";”代碼揪惦,底層執(zhí)行機(jī)制如下:
(1).程序優(yōu)先調(diào)用"name;"代碼來獲取該getter方法的返回值。
(2).如果該類沒有name方法罗侯,KVC機(jī)制會搜索該類名為name的成員變量器腋,找到后返回name成員變量的值。
(3).如果該類既沒有name方法钩杰,也沒有定義_name成員變量纫塌,KVC機(jī)制會搜索該類名為name的成員變量,找到后返回name成員變量的值讲弄。
(4).如果上面3條都沒有找到措左,系統(tǒng)將會執(zhí)行該對象的valueForUndefinedKey:方法。默認(rèn)valueForUndefinedKey:方法會引發(fā)一個異常避除,將會導(dǎo)致程序崩潰怎披。
Adopting Key-Value Coding
Using a @propertystatement, allowing the compiler to automatically synthesize the ivar and accessors.
@property 自動為屬性配置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 為屬性動態(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