iOS之KVC

KVC,即是指 Key Value Coding,一个非正式的 Protocol,提供一种机制来间接访问对象的属性。KVC是实现KVO的基础。

一个对象拥有某些属性。比如一个Person对象有一个name和一个address属性。则Person对象分别有一个value对应他的nameaddress的key。 key只是一个字符串,它对应的值可以是任意类型的对象。从最基础的层次上看,KVC 有两个方法:一个是设置key的值,另一个是获取key的值。如下面的例子:

1
2
3
4
5
6
7
8
9
-(void)changePerson:(Person *)p name:(NSString *)newName
{
// using the KVC accessor (getter) method
NSString *originalName = [p valueForKey:@"name"];
// using the KVC accessor (setter) method.
[p setValue:newName forKey:@"name"];
NSLog(@"Changed %@'s name to: %@", originalName, newName);

}
现在,如果 Person 有另外一个 key 配偶(spouse),spouse 的 key 值是另一个 Person 对象,用 KVC 可以这样写:
1
2
3
4
5
6
7
8
9
10
11
-(void)getMarriage:(Person *)p
{
// just using the accessor again, same as example above
NSString *personsName = [p valueForKey:@"name"];

// this line is different, because it is using
// a "key path" instead of a normal "key"
NSString *spousesName = [p valueForKeyPath:@"spouse.name"];
NSLog(@"%@ is happily married to %@", personsName, spousesName);

}

key与keyPath要区分开来,key可以从一个对象中获取值,而keyPath可以将多个 key 用点号 “.” 分割连接起来,比如:

1
[p valueForKeyPath:@"spouse.name"];

相当于:

1
[[p valueForKey:@"spouse"] valueForKey:@"name"];