gpt4 book ai didi

iphone - 为过滤器构建 NSPredicate

转载 作者:太空狗 更新时间:2023-10-30 03:39:53 26 4
gpt4 key购买 nike

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

这基本上是用于过滤器,因此如果未选择某些选项,我不会按它们进行过滤

例如。如果我为过滤器设置了选项 1 和选项 2。

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

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

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

谢谢

最佳答案

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

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

罗布。

关于iphone - 为过滤器构建 NSPredicate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2643530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com