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

 

 

转载于:https://www.cnblogs.com/simalone/p/3836298.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值