6

只是想知道如果某些过滤器是可选的,那么构建 NSPredicate 的最佳方法是什么?

这基本上是一个过滤器,所以如果没有选择某些选项,我不会按它们过滤

例如。如果我为过滤器设置了 option1 和 option2。

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"option1 = %@ AND option2 = %@] ....

否则如果只是 option1 NSPredicate* predicate = [NSPredicate predicateWithFormat:@"option1 = %@] ....

关键是有 10 种不同的过滤选项,所以我不想为 10x10 可能的组合编码。

谢谢

4

2 回答 2

17

约翰,看看构建和保留“子谓词”作为模板,然后使用您的逻辑分支构建复合谓词来执行过滤

/* Retain these predicate templates as properties or static variables */
NSPredicate *optionOneTemplate = [NSPredicate predicateWithFormat:@"option1 = $OPTVALUE"];
// .. and so on for other options

NSMutableArray *subPredicates = [NSMutableArray arrayWithCapacity:10];

/* add to subPredicates by substituting the current filter value in for the placeholder */
if (!!optionOneValue) {
  [subPredicates addObject:[optionOneTemplate predicateWithSubstitutionVariables:[NSDictionary dictionaryWithObject:optionOneValue forKey:@"OPTVALUE"]]];
}
// .. and so on for other option values

/* use the compound predicate to combine them */
NSPredicate *filterPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];

// Now use your filterPredicate

您可能希望使用字典来保持谓词模板集井井有条,但上面的示例显示了基本步骤。

抢。

于 2010-04-15T18:42:39.400 回答
1

predicateWithFormat:接受一个 NSString。因此,您所要做的就是根据所选选项构建字符串(使用 for 循环附加到 NSMutableString 等)并将其传递给predicateWithFormat:

于 2010-04-15T08:02:04.737 回答