码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-07-16 21:06:26      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   使用   os   for   

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

 

 

KVC通过Key获取对应的Value的顺序,布布扣,bubuko.com

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

标签:style   blog   color   使用   os   for   

原文地址:http://www.cnblogs.com/simalone/p/3836298.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!