【问题标题】:Building a NSPredicate for a filter为过滤器构建 NSPredicate
【发布时间】:2011-02-08 06:26:51
【问题描述】:

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

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

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

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

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

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

谢谢

【问题讨论】:

    标签: iphone objective-c cocoa core-data nspredicate


    【解决方案1】:

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

    /* 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
    

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

    罗伯。

    【讨论】:

    • 您能否进一步了解如何将谓词模板保存在静态变量中?
    【解决方案2】:

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

    【讨论】:

    • 不确定那是完全正确的 这有效:[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"startTime >= %@", from]];这会崩溃:[fetchRequest setPredicate:[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"startTime >= %@", from]]];
    • 约翰:那是因为你添加了stringWithFormat:。不要那样做。改用 Diederik 的建议(或使用 componentsJoinedByString:,它会为您执行循环)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多