在NSPredicates中使用关键路径

nep*_*lim 4 objective-c key-value-observing key-value-coding

我有一个NSDictionary,其中包含(我的自定义)GTPerson对象.GTPerson有一个NSMutableSet *parents属性,我使用@property@synthesize.

在我的NSDictionary之外,我想过滤掉所有没有父母的GTPerson对象,即父母的数量是0.

我正在使用以下代码:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parents.count = 0"];
NSArray *np = [[people allValues] filteredArrayUsingPredicate:predicate];
Run Code Online (Sandbox Code Playgroud)

当我执行此操作时,我收到以下错误:

[<GTPerson 0x18e300> valueForUndefinedKey:]: this class is not key value coding-compliant for the key count.

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<GTPerson 0x18e300> valueForUndefinedKey:]: this class is not key value coding-compliant for the key count.'

为什么它试图调用countGTPerson而不是它的parents属性?

Jim*_*eia 15

你的问题的解决方案是使用运营商@count@"parents.@count == 0".

读取异常,我们看到评估谓词将消息发送-count到GTPerson对象.为什么?

发送-valueForKey:到集合(在您的情况下,集合是NSSet,它是评估parents密钥路径的组件的结果)发送-valueForKey:到集合中的每个对象.

在这种情况下,导致-valueForKey: @"count"发送到每个GTPerson实例,而GTPerson不是符合计数的键值编码.

相反,@count当您需要集合的计数时,使用运算符来计算集合的计数,而不是集合中count所有对象的键值.