【问题标题】:NSPredicate of NSArray in NSDictionaryNSDictionary 中 NSArray 的 NSPredicate
【发布时间】:2013-01-02 14:52:22
【问题描述】:

我的数组

(
   {id:1,data:(@"macbook",@"mac mini")},
   {id:2,data:(@"ipad",@"ipod")},
   {id:3,data:(@"macbook",@"ipod")}
)

我有一个谓词

NSString *text = @"mac";
[NSPredicate predicateWithFormat:@"(data contains[cd] %@)",text];
[array filteredArrayUsingPredicate:predicate];

但它不会遍历我字典中的数组 (我的结果应该是一个包含 2 个 id 为 1 和 3 的对象的数组)

【问题讨论】:

  • 你能告诉我们你是如何初始化你的数组的吗?你确定你在array 变量中有你的想法吗?
  • 你可以这样做,但会很棘手。 Dave DeLong 在这里给出了答案:stackoverflow.com/a/4831366/312312

标签: iphone objective-c ios nspredicate predicate


【解决方案1】:
NSString* text = @"mac" ;
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"any data contains[cd] %@",text] ;
NSArray* filteredArray = [theArray filteredArrayUsingPredicate:predicate] ;

【讨论】:

    【解决方案2】:

    我个人觉得NSPredicate 格式很容易出错。

    您可以考虑使用块来过滤您的NSArray

    NSString * filterString = @"mac";
    NSIndexSet * indexes = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        NSArray * entry = obj[@"data"];
        for (NSString * value in entry)
            if ([value rangeOfString:filterString].location != NSNotFound)
                return YES;
        return NO;
    }];
    NSArray * filteredArray = [array objectsAtIndexes:indexes];
    

    它肯定更长更冗长,但我发现它肯定更容易阅读和调试。

    【讨论】:

      猜你喜欢
      • 2016-01-22
      • 2012-08-02
      • 2012-05-17
      • 2010-10-31
      • 1970-01-01
      • 2015-05-07
      • 2017-01-31
      • 2013-11-20
      • 1970-01-01
      相关资源
      最近更新 更多