【问题标题】:Replacing a variable in an NSPredicate替换 NSPredicate 中的变量
【发布时间】:2014-02-15 19:47:39
【问题描述】:

我的NSPredicate

[NSPredicate predicateWithFormat:@"$1.employees.@count == 50"] ;

如何通过将$1 替换为self(或什么都不用)从这个中获得一个新的NSPredicate?我怎样才能得到谓词

[NSPredicate predicateWithFormat:@"self.employees.@count == 50"] ;

我不想评估我的谓词,我想要一个新的谓词。

【问题讨论】:

    标签: ios macos core-data nspredicate


    【解决方案1】:

    您可以从“谓词模板”创建谓词。但是,$1 不是有效的 谓词模板中的变量和

    [NSPredicate predicateWithFormat:@"$1.employees.@count == 50"]
    

    实际上会导致运行时异常。但以下工作,应该证明这个想法:

    NSPredicate *p1 = [NSPredicate predicateWithFormat:@"$foo.employees.@count == 50"] ;
    NSLog(@"%@", p1);
    // $foo.employees.@count == 50
    
    // Substitute $foo by self:
    NSPredicate *p2 = [p1 predicateWithSubstitutionVariables:@{@"foo": [NSExpression expressionForEvaluatedObject]}];
    NSLog(@"%@", p2);
    // employees.@count == 50
    
    // Substitute $foo by "bar":
    NSPredicate *p3 = [p1 predicateWithSubstitutionVariables:@{@"foo": [NSExpression expressionForKeyPath:@"bar"]}];
    NSLog(@"%@", p3);
    // bar.employees.@count == 50    
    

    欲了解更多信息,请参阅"Creating Predicates Using Predicate Templates" 在“谓词编程指南”中。

    【讨论】:

    • 我爱你@Martin =8-°
    • 是的,你是对的,我在等着看看是否有人会提供更好的东西......但这怎么可能呢?
    • 也许你会对这个话题有所了解:stackoverflow.com/q/21823339/1670830。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2013-12-30
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多