iOS Objective-C 如何使用谓词在字符串数组中搜索多个非连续关键字?

iOS Objective-C how to use a predicate to search a string array for multiple non-sequential keywords?

我正在使用以下代码搜索数组,return搜索包含部分搜索查询的项目。当搜索查询是单个词或词的一部分时,这很有效:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"comment.text CONTAINS [cd] %@ ",_searchQuery];
NSArray *result = [_sourceArray filteredArrayUsingPredicate:predicate];

如何扩展我的谓词以接受包含多个词的搜索查询和包含查询中所有词的 return 结果?

例如:

下面的代码列举了 _searchQuery 中的单词,为每个单词创建一个谓词,然后使用 AND:

将它们组合成一个 NSCompoundPredicate
NSMutableArray *subpredicates = [NSMutableArray new];
[_searchQuery enumerateSubstringsInRange:NSMakeRange(0, _searchQuery.length)
                                 options:NSStringEnumerationByWords
                              usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                           NSPredicate *subpredicate = [NSPredicate predicateWithFormat:@"comment.text CONTAINS [cd] %@ ",substring];
                           [subpredicates addObject:subpredicate];
                       }];

NSCompoundPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subpredicates];
NSArray *result = [_sourceArray filteredArrayUsingPredicate:compoundPredicate];

如果关键字的顺序对您很重要,您可以使用正则表达式来完成这项工作:

NSArray *const source = @[@"apples and oranges are fruits"];

static NSString *const separator = @".*";
NSArray *const keywords = @[@"apples", @"oranges"];
NSString *const pattern = [NSString stringWithFormat:@"%@%@%@", separator, [keywords componentsJoinedByString:separator], separator];
NSPredicate *const predicate = [NSPredicate predicateWithFormat:@"self MATCHES %@", pattern];

NSArray *const filtered = [source filteredArrayUsingPredicate:predicate];

否则你可以 OR 一对 CONTAINS 在一起,就像@Larme 建议的那样。