【问题标题】:Reuse NSPredicate for new variable substitute重用 NSPredicate 来替换新的变量
【发布时间】:2011-10-10 04:28:37
【问题描述】:

我可以重复使用 NSPredicate 来替代新的变量吗?我的 NSPredicate 相当简单:

NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"id == %@",userID];

用户ID 是在运行时生成的,具有不同的值,现在我需要为每个用户ID 创建一个NSPredicate。那么我可以重用我的 NSPredicate 吗?

【问题讨论】:

    标签: cocoa core-data nspredicate


    【解决方案1】:

    是的,你可以用一个变量来做到这一点:

    NSPredicate *userPredicate = [NSPredicate predicateWithFormat:@"id == $user"];
    

    将该谓词保存在某处,然后在您需要实际开始过滤内容时执行此操作:

    NSDictionary *sub = [NSDictionary dictionaryWithObject:user forKey:@"user"];
    NSPredicate *filter = [userPredicate predicateWithSubstitutionVariables:sub];
    

    这是重用谓词的一种更有效的方法,因为解析格式字符串(可能非常昂贵)只发生一次。

    【讨论】:

    • 你知道我们是否可以对键应用变量替换吗?实际上似乎它们被替换为引号,并使查询无法使用。
    • @Leonardo 我不这么认为。 AFAIK,变量只能被常量值替换,而不是键路径。
    • 我可以用一个键进行多个替换吗?
    • @atreat 是的,你可以让$user 在谓词中出现多次。
    • @Leonardo @DaveDeLong 您可以通过在替换字典中使用["myKey": NSExpression(forKeyPath: theKey)] 来使用键进行变量替换。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2014-01-09
    • 2013-04-24
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多