【问题标题】:Obj-C - Filter NSMutableArray with another array?Obj-C - 用另一个数组过滤 NSMutableArray?
【发布时间】:2021-08-15 20:20:07
【问题描述】:

我有一个 NSMutableArray (self.allPeople) 包含许多字典(人)。也就是说,我还有一个包含一系列数字的 NSMutableArray (self.participants):

self.participants

Here they are: (
    179,
    125,
    231
)

我想要过滤 self.allPeople,并且只返回键“nid”等于 self.participants 中包含的数字之一的字典。

如何使用 self.participants 中的每个数字过滤 self.allPeople (valueForKey:@"nid")?

如果我只想按单个字符串值进行过滤,但我需要它来过滤所有数字,则此方法有效:

  NSPredicate *p = [NSPredicate predicateWithFormat:@"nid CONTAINS[cd] %@", @"179"];
  self.results = [self.allPeople filteredArrayUsingPredicate:p];

【问题讨论】:

    标签: ios objective-c nspredicate


    【解决方案1】:

    只需将IN 用于数组,如下所示:

    NSArray<NSDictionary<NSString *, NSNumber *> *> *allPeople = @[
        @{ @"nid": @120 },
        @{ @"nid": @121 },
        @{ @"nid": @122 },
        @{ @"nid": @123 },
    ];
    NSArray<NSNumber *> *participants = @[ @120, @123 ];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"nid IN %@", participants];
    NSArray<NSDictionary<NSString *, NSNumber *> *> *results = [allPeople filteredArrayUsingPredicate:predicate];
    NSLog(@"RESULTS: %@", results);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-08
      • 2017-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多