【问题标题】:Why doesn't this NSPredicate work?为什么这个 NSPredicate 不起作用?
【发布时间】:2010-06-28 16:54:39
【问题描述】:

我有一个非常简单的 NSPredicate:

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"name beginswith '%@'", theString];
[matchingTags filterUsingPredicate:sPredicate];

这会导致数组在 theString == "p" 时有 0 个结果

但是,当我这样做时:

NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"name beginswith 'p'"];
[matchingTags filterUsingPredicate:sPredicate];

正如预期的那样,我得到了 100 多个结果。

我用 NSLog() 检查了“theString”,它的值是正确的。我觉得我错过了一些重要的秘密。可能是因为我使用的是字符串而不是字符?

想法?

【问题讨论】:

    标签: iphone objective-c string predicate nspredicate


    【解决方案1】:

    查看文档here

    如果您使用变量替换 %@(如 firstName like %@), 为您添加引号 自动。

    所以基本上,它正在寻找以“p”开头的名称,而不是 p。将您的代码更改为:

    NSPredicate *sPredicate = [NSPredicate predicateWithFormat:@"name beginswith %@", theString];
    

    应该工作

    【讨论】:

    • 该死的,我以为我已经尝试过了。但是,是的,就是这样。谢谢!
    猜你喜欢
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 2013-03-10
    相关资源
    最近更新 更多