使用KeyValue Coding

之前的一篇文章介绍了实现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"];
原文地址:https://www.cnblogs.com/whyandinside/p/2944069.html