为过滤器构建NSPredicate

Joh*_*ohn 6 iphone cocoa core-data objective-c nspredicate

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

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

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

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

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

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

谢谢

ohh*_*rob 17

John,看一下构建并保留"子谓词"作为模板,然后使用逻辑分支构建复合谓词来执行过滤

/* 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
Run Code Online (Sandbox Code Playgroud)

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

抢.