开发者

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

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 predica开发者_如何学Cte. But I thought I’d ask if there is a built-in way to do this, before doing that.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜