【问题标题】:Using key paths in NSPredicates在 NSPredicates 中使用关键路径
【发布时间】:2009-07-31 15:08:44
【问题描述】:

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

在我的 NSDictionary 中,我想过滤所有没有任何父母的 GTPerson 对象,即父母的数量为 0。

我正在使用以下代码:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"parents.count = 0"];
NSArray *np = [[people allValues] filteredArrayUsingPredicate:predicate];

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

[<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.'

为什么它试图在 GTPerson 上调用 count 而不是在其 parents 属性上?

【问题讨论】:

    标签: objective-c key-value-observing key-value-coding


    【解决方案1】:

    解决您的问题的方法是使用运算符@count,如@"parents.@count == 0"

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

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

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

    当您需要集合的计数时,请使用 @count 运算符来评估集合的计数,而不是集合中所有对象上的键 count 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多