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