编写NSPredicate格式字符串以测试多个属性的更短方法?

Sve*_*ven 1 cocoa objective-c nspredicate

是否有更短的方法为谓词等效于此编写格式字符串:

[NSPredicate predicateWithFormat: @"key1 CONTAINS[cd] %@ OR key2 CONTAINS[cd] %@ OR key3 CONTAINS[cd] %@", searchString, searchString, searchString];
Run Code Online (Sandbox Code Playgroud)

我已经编写了一些这样的谓词格式字符串,我正在考虑通过编写一个方法来简化它,该方法采用一系列关键路径和搜索字符串来构造这样的谓词.但在我这样做之前,我想我会问是否有内置方法可以做到这一点.

Bar*_*obs 6

NSCompoundPredicate是的一个子类NSPredicate,并接受一个NSArrayNSPredicate实例.但是,这意味着您仍然必须自己构建NSPredicate对象(如果您愿意,还可以构建子对象).我的建议是编写自己的方法(正如您计划的那样),但请使用NSCompoundPredicate它,因为它是为此目的而设计的.

- (NSPredicate *)predicateWithKeyPaths:(NSArray *)keyPaths andSearchTerm:(NSString *)searchTerm {
NSMutableArray *subpredicates = [[NSMutableArray alloc] init];

for (NSString *keyPath in keyPaths) {
    NSPredicate *subpredicate = [NSPredicate predicateWithFormat:@"%K CONTAINS[cd] %@", keyPath, searchTerm];
    [subpredicates addObject:subpredicate];
}

NSPredicate *result = [NSCompoundPredicate orPredicateWithSubpredicates:subpredicates];
[subpredicates release];

return result;}
Run Code Online (Sandbox Code Playgroud)