编写NSPredicate格式字符串以测试多个属性的更简单的方法? [英] Shorter way to write NSPredicate format string for testing multiple properties?

查看:252
本文介绍了编写NSPredicate格式字符串以测试多个属性的更简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个较短的方法来写一个等价于这个谓词的格式化字符串:

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.

推荐答案

NSCompoundPredicate NSPredicate 的子类,并使用 NSArray c $ c> NSPredicate 实例。然而,这意味着你仍然必须自己构造 NSPredicate 对象(子predpredicates)。我的建议是写你自己的方法(如你计划),但使用 NSCompoundPredicate ,因为它是为此目的设计的。

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

这篇关于编写NSPredicate格式字符串以测试多个属性的更简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆