Key-value codingis a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables. In essence, key-value coding defines the patterns and method signatures that your application’s accessor methods implement.
Listing 1 Implementation of data-source method without key-value coding
- (id)tableView:(NSTableView *)tableview |
objectValueForTableColumn:(id)column row:(NSInteger)row {
|
|
|
ChildObject *child = [childrenArray objectAtIndex:row]; |
if ([[column identifier] isEqualToString:@"name"]) {
|
return [child name]; |
} |
if ([[column identifier] isEqualToString:@"age"]) {
|
return [child age]; |
} |
if ([[column identifier] isEqualToString:@"favoriteColor"]) {
|
return [child favoriteColor]; |
} |
// And so on. |
} |
Listing 2 Implementation of data-source method with key-value coding
- (id)tableView:(NSTableView *)tableview |
objectValueForTableColumn:(id)column row:(NSInteger)row {
|
|
|
ChildObject *child = [childrenArray objectAtIndex:row]; |
return [child valueForKey:[column identifier]]; |
} |
本文介绍了一种称为键值编码(Key-Value Coding, KVC)的技术,该技术允许通过字符串间接访问对象属性,而不需要直接调用访问器方法或通过实例变量访问。通过两个实现数据源方法的例子对比,展示了使用KVC可以显著减少代码量并提高灵活性。
386

被折叠的 条评论
为什么被折叠?



