KVC通过Key获取对应的Value的顺序

KVC,即NSKeyValueCoding,通过字符化名字作为Key来访问对象属性的机制。本质上,KVC在某种程度上提供了访问器的替代方案,只要是有可能KVC尽量使用访问器方法。

以返回对象属性key例,KVC按如下顺序查找返回值:

1、-(<type>) getKey访问器方法

2、-(<type>) key

3、调用valueForUndefinedKey:方法。这些方法的默认实现都是抛出异常。

4、抛出一个NSUndefinedKeyException异常错误。

 

使用KVC在某些情况下可简化代码,如下:

// 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.
}

//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]];
}

 

 

posted @ 2014-07-10 17:55  simalone  阅读(437)  评论(0编辑  收藏  举报