【问题标题】:Filtering NSArray of NSDictionary objects using NSPredicate使用 NSPredicate 过滤 NSDictionary 对象的 NSArray
【发布时间】:2012-05-17 07:44:53
【问题描述】:

我有一个 NSDictionary 对象的 NSArray。我想使用 NSPredicate 根据字典的键过滤数组。我一直在做这样的事情:

NSString *predicateString = [NSString stringWithFormat:@"%@ == '%@'", key, value];
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredResults = [allResultsArray filteredArrayUsingPredicate:predicate];

如果他们传入的键是一个词:颜色、姓名、年龄,这很好用。但如果 key 是多词则不起作用,例如:Person Age、Person Name。

基本上,任何包含空格的键都不起作用。我尝试在字符串中的键周围加上单引号,就像它们在值方面完成一样,但这也不起作用。也试过双引号,但无济于事。

请就此提出建议。提前致谢。

【问题讨论】:

标签: iphone ios nsarray nsdictionary nspredicate


【解决方案1】:

对我来说,凯文的回答不起作用。我用过:

NSPredicate *predicateString = [NSPredicate predicateWithFormat:@"%K contains[cd] %@", keySelected, text];//keySelected is NSString itself
        NSLog(@"predicate %@",predicateString);
        filteredArray = [NSMutableArray arrayWithArray:[YourArrayNeedToFilter filteredArrayUsingPredicate:predicateString]];

【讨论】:

  • 对于那些在家玩的人来说,可选的[cd] 让您不区分大小写和变音符号。
【解决方案2】:

使用动态密钥时,您应该使用%K 令牌而不是%@。您也不希望值标记周围的引号。它们将使您的谓词针对文字字符串 @"%@" 而不是针对 value 测试是否相等。

NSString *predicateString = [NSString stringWithFormat:@"%K == %@", key, value];

这在Predicate Format String Syntax guide 中有记录。


编辑:正如 Anum Amin 指出的那样,+[NSString stringWithFormat:] 不处理谓词格式。你想要[NSPredicate predicateWithFormat:@"%K == %@", key, value]

【讨论】:

  • NSString 不会正确替换 %K。应该使用[NSPredicate predicateWithFormat:]。请参阅下面的答案。
  • @AnumAmin:你说得对。我想这就是我试图“修复”Bittu 的代码而不是重新创建它的结果。我很惊讶他竟然接受了我的回答。
  • 我已经在使用 NSPredicate predicateWithFormat: 所以,在那个语句中很容易做到这一点,而不是一个单独的语句来创建一个 NSString。我应该在评论中澄清它,但 Anum 做得很好:)
猜你喜欢
  • 2013-11-20
  • 2012-08-02
  • 2010-10-31
  • 2016-09-29
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多