【问题标题】:How do you filter an NSArray with an Array of NSPredicates?如何使用 NSPredicates 数组过滤 NSArray?
【发布时间】:2015-02-12 18:49:33
【问题描述】:

我知道你可以做类似 [..."SELF.some_id == [c] %d AND SELF.some_id == [c] %d", id1, id2] 的事情,但我需要的不止这些。有没有办法在不构建字符串的情况下做到这一点。

例如...

NSArray *arrayOfWantedWidgetIds = @[1,3,5,6,9,13,14,16];
NSMutableArray *allWidgets = [[WidgetManager sharedWidget] getAllWidgets];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.widget_id ==[c] %d", arrayOfWantedWidgetIds]; //obviously we can't do this, it won't accept an array of IDS for %d
[allWidgets filterArrayUsingPredicate:predicate];

我怎样才能实现这样的目标?另一种方式......如果我循环这个,并为arrayOfWantedWidgetIds中的每个值制作单独的谓词,然后将所有单独的谓词添加到一个数组中......这也无济于事,因为filterArrayUsingPredicate只接受一个NSPredicate。不是它们的数组。

【问题讨论】:

    标签: objective-c cocoa nsarray nspredicate


    【解决方案1】:

    您不能像这样将数组传递给谓词 API。但是,您可以传递一个 ID 数组,并使用 IN 运算符,这在您的特定情况下应该足够了:

    NSArray *arrayOfWantedWidgetIds = @[@1, @3, @5, @6, @9, @13, @14, @16];
    NSMutableArray *allWidgets = [[WidgetManager sharedWidget] getAllWidgets];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.widget_id IN %@", arrayOfWantedWidgetIds];
    [allWidgets filterArrayUsingPredicate:predicate];
    

    您也可以用NSCompoundPredicate 构造一个复合谓词,但在这种情况下这是不必要的。

    【讨论】:

    • 您还可以使用NSCompoundPredicate对多个谓词进行分组
    【解决方案2】:

    查看 in 运算符

        NSArray *idList = @[@1,@2,@3,@5,@7];
        NSMutableArray *widgetList = [[NSMutableArray alloc] init];
        for (int i=0; i<20; i++) {
            [widgetList addObject:[[widgets alloc] init]];
        }
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.widget_id in %@",idList];
        NSLog(@"%@",[widgetList filteredArrayUsingPredicate:predicate].debugDescription);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      相关资源
      最近更新 更多