【问题标题】:Using NSPredicate to filter NSArray by keywords使用 NSPredicate 按关键字过滤 NSArray
【发布时间】:2017-06-21 21:49:57
【问题描述】:

我有一个名为 myArray 的 NSArray。我想过滤myArray 对象,以便我排除该数组中与另一个数组keywords 中的关键字相对应的所有元素。

所以,这就是我的伪代码:

keywords = @[@"one", @"three"];
myArray = @[@"textzero", @"textone", @"texttwo", @"textthree", @"textfour"];
predicate = [NSPredicate predicateWithFormat:@"NOT (SELF CONTAINS_ANY_OF[cd] %@), keywords];
myArray = [myArray filteredArrayUsingPredicate:predicate];

这就是我想通过NSLog(@"%@", myArray)得到的

>> ("textzero", "texttwo", "textfour")

我该怎么做?

【问题讨论】:

    标签: macos cocoa nsarray nspredicate predicatewithformat


    【解决方案1】:

    使用此代码:

    NSArray *keywords = @[@"one", @"three"];
    NSArray *myArray = @[@"textzero", @"textone", @"texttwo", @"textthree", @"textfour"];
    NSString * string = [NSString stringWithFormat:@"NOT SELF CONTAINS[c] '%@'", [keywords componentsJoinedByString:@"' AND NOT SELF CONTAINS[c] '"]];
    NSPredicate* predicate = [NSPredicate predicateWithFormat:string];
    NSArray* filteredData = [myArray filteredArrayUsingPredicate:predicate];
    NSLog(@"Complete array %@", filteredData);
    

    【讨论】:

      【解决方案2】:

      您可以使用块来过滤数组。通常一个块更快。

      keywords = @[@"one", @"three"];
      myArray = @[@"textzero", @"textone", @"texttwo", @"textthree", @"textfour"];
      predicate = [NSPredicate predicateWithBlock:^(NSString *evaluatedObject, NSDictionary<NSString *,id> *bindings){
          for (NSString *key in keywords)
              if ([evaluatedObject rangeOfString:key options:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch].location != NSNotFound)
                  return NO;
          return YES;
      }];
      myArray = [myArray filteredArrayUsingPredicate:predicate];
      

      keywords = @[@"one", @"three"];
      myArray = @[@"textzero", @"textone", @"texttwo", @"textthree", @"textfour"];
      NSIndexSet *indices = [myArray indexesOfObjectsPassingTest:^(NSString *obj, NSUInteger idx, BOOL *stop){
          for (NSString *key in keywords)
              if ([obj rangeOfString:key options:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch].location != NSNotFound)
                  return NO;
          return YES;
      }];
      myArray = [myArray objectsAtIndexes:indices];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-31
        • 2012-08-02
        • 2012-06-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多