Shorter way to write NSPredicate format string for testing multiple properties?

倾然丶 夕夏残阳落幕 提交于 2019-12-08 06:56:47

问题


Is there a shorter way to write the format string for a predicate equivalent to this:

[NSPredicate predicateWithFormat: @"key1 CONTAINS[cd] %@ OR key2 CONTAINS[cd] %@ OR key3 CONTAINS[cd] %@", searchString, searchString, searchString];

I have written a few predicate format strings like this, and I was thinking to simplify that by writing a method that takes an array of key paths and the search string to construct such a predicate. But I thought I’d ask if there is a built-in way to do this, before doing that.


回答1:


NSCompoundPredicate is a subclass of NSPredicate and takes an NSArray of NSPredicate instances. However, this would mean that you still have to construct the NSPredicate objects (the subpredicates if you will) yourself. My suggestion is to write your own method (as you are planning to) but use NSCompoundPredicate as it is designed for this purpose.

- (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;}



回答2:


I don't believe there is a shorter way. An alternative is to use NSCompoundPredicate's orPredicateWithSubpredicates: method. That's hardly shorter, but probably not as "boring" as having to concatenate strings.



来源:https://stackoverflow.com/questions/6305940/shorter-way-to-write-nspredicate-format-string-for-testing-multiple-properties

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!