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

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

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

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

二、-(<type>) key对象

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

四、抛出一个NSUndefinedKeyException异常错误。get

 

使用KVC在某些状况下可简化代码,以下:it

// 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]];
}
相关文章
相关标签/搜索