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]];
}
相關文章
相關標籤/搜索