之前的一篇文章介紹了實現Key-Value Coding的5種方法,但用的最多的還是基於NSKeyValueCoding協議的。本文介紹的都是基於這個前提的。
key是啥?
A key is a string that identifies a specific property of an object. Typically, a key corresponds to the name of an accessor method or instance variable in the receiving object. Keys must use ASCII encoding, begin with a lowercase letter, and may not contain whitespace. 比如 abc, payee, employeeCount等。
key path是啥?
A key path is a string of dot separated keys that is used to specify a sequence of object properties to traverse. The property of the first key in the sequence is relative to the receiver, and each subsequent key is evaluated relative to the value of the previous property.比如address.street,會先從receiving object中找到key:address的value, 然后從這個value object中找出key:street這個value。
由於Objective C的key是支持attribute, to-one, to-many relationship 的,key path 也是支持的,比如一個key path:transactions.payee,它表示的是所有transaction的payee,而accounts.transactions.payee則表示所有帳號的所有的transaction的payee。
下面是常用APIs:
valueForKey:
valueForKeyPath:
dictionaryWithValuesForKeys: 輸入一組key,返回這組key的所有值;
setValue:forKey:
setValue:forKeyPath:
setValuesForKeysWithDictionary: 輸入一個key-value的dictionary,調用setValue:forKey:進行一個一個的設置操作;
Dot Syntax 與KVC 的關系
Dot Syntax 與KVC 是正交的,其實沒什么關系,但有時他們可以達到相同的效果,比如下面的類定義:
@interface MyClass @property NSString *stringProperty; @property NSInteger integerProperty; @property MyClass *linkedInstance; @end
下面是用Dot Syntax實現的:
MyClass *anotherInstance = [[MyClass alloc] init]; myInstance.linkedInstance = anotherInstance; myInstance.linkedInstance.integerProperty = 2;
其效果跟下面KVC方式相同:
MyClass *anotherInstance = [[MyClass alloc] init]; myInstance.linkedInstance = anotherInstance; [myInstance setValue:@2 forKeyPath:@"linkedInstance.integerProperty"];