2017-06-21 117 views
1

我有一个名为myArray的NSArray。我想过滤myArray对象,因此我排除了该数组中所有对应于来自另一个数组keywords的关键字的元素。使用NSPredicate按关键字过滤NSArray

所以,这是我的伪代码:

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") 

我应该怎么做才能得到?

回答

0

使用此代码:

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); 
0

您可以使用块阵列进行过滤。通常块更快。

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];