KVC - 带点分隔的键值编码 - 不符合 KVC 的例外

KVC - key value coding with dot seperation - Exception not KVC compliant

@interface MyClass: NSObject
@property NSArray *arr;
@end
@inplementation MyClass
- (instancetype) init
{
    if(self = [super init])
    {
        self.arr = [[NSArray alloc] init];
    }
    return self;
}
@end
int main(int argc, char *argv[])
{
    MyClass *temp = [[MyClass alloc] init];
    [temp valueForKey:@"arr.count"];    //count is ivar of NSArray
    return 0;
}

然后控制台说

NSExceptions: [MyClass valueForUnfinedKey:] this class is not key value-complaint for the key arr.count

每次我用点分隔符,这个exceptions就出来了。

我试过搜索网页和阅读菜单,我仍然不知道为什么,有人可以帮忙吗?谢谢

因为arr.count不是MyClass的key-value-complaint。程序运行时,找不到任何 属性 of MyClass name arr.count.

valueForKeyPath: - Returns the value for the specified key path relative to the receiver. Any object in the key path sequence that is not key-value coding compliant for a particular key—that is, for which the default implementation of valueForKey: cannot find an accessor method—receives a valueForUndefinedKey: message.

方法 valueForKey: 采用单个键(属性 或局部变量)名称,它不采用键路径,例如您的 arr.count.

方法 valueForKeyPath: 确实采用了关键路径,它实际上是一系列 valueForKey: 调用。请参阅 About Key-Value Coding 中的使用键获取属性值

但是 由于 NSArray 的定义方式 valueForKey::

,您的示例仍然无法工作

Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.

所以在你的情况下,如果你尝试 valueForKeyPath:@"arr.count",路径的 arr 部分将 return 你的数组然后 NSArrayvalueForKey:将尝试为数组的每个元素获取 count 并为数组本身获取 not。不是你想要的...

这将我们带到 Collection Operators,它提供了对集合(在您的情况下是数组)而不是其元素进行操作的关键路径。你需要的集合算子是@count给你关键路径arr.@count,所以你需要调用:

[temp valueForKeyPath:@"arr.@count"]

除非这是学习 KVC 的练习,否则可以缩短为:

temp.arr.count

没有尝试将 count 应用于数组元素的问题,并且 return 是 NSUInteger 值而不是 NSNumber 实例。

HTH