【问题标题】:NSPredicate - Unable to parse the format string [duplicate]NSPredicate - 无法解析格式字符串 [重复]
【发布时间】:2013-04-27 19:54:12
【问题描述】:

我正在尝试编写一个NSPredicate 以使用此字符串“193e00a75148b4006a451452c618ccec”获取具有 my_column 值的行,但出现以下崩溃。

由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'无法解析格式 字符串“my_column=193e00a75148b4006a451452c618ccec”'

我的谓词陈述

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==\"%@\"",attributeName,itemValue]];

也试过了

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@",attributeName,itemValue]];

这个

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = %@",attributeName,itemValue]];

还有这个

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@=\"%@\"",attributeName,itemValue]];

请帮忙。

我在尝试 Martin R 的回答时发现了这一点

fetchRequest.predicate=[NSPredicate predicateWithFormat:@"%@==%@",attributeName,itemValue];

我传递的attributeName 带有一个'',所以我去掉了attributeName 并对其进行了硬编码,然后它就可以正常工作了。

【问题讨论】:

  • 在比较字符串时使用 LIKE 而不是 '='!
  • 使用占位符时不需要引号。
  • @VinayakKini:通常不应该使用“LIKE”来比较字符串,因为 LIKE 会使用通配符匹配“*”和“?”有特殊意义。
  • @MartinR 感谢您的信息!

标签: ios core-data nspredicate


【解决方案1】:

用单引号将字符串括起来:

[NSPredicate predicateWithFormat:@"my_column = '193e00a75148b4006a451452c618ccec'"]

更好,使用参数替换:

[NSPredicate predicateWithFormat:@"my_column = %@", @"193e00a75148b4006a451452c618ccec"]

如果搜索字符串包含特殊字符,第二种方法可以避免出现问题 比如'"

备注: 构建谓词时切勿使用stringWithFormatstringWithFormatpredicateWithFormat 以不同方式处理 %K%@ 格式,因此将这些组合起来 两种方法非常容易出错(并且不必要)。

【讨论】:

  • 我都试过了,没有效果。
  • @satheeshwaran:在构建谓词时不要使用stringWithFormat!!!请按照我在答案中写的完全尝试。
  • 嘿@Martin R 我也这样做了,没用:-(。
  • @satheeshwaran:请显示您尝试过的确切代码。
  • 我已经发布了我上面尝试的所有代码。
【解决方案2】:

我认为您在检查相等性时错过了 '',

现在试试,

[NSPredicate predicateWithFormat:@"my_column='193e00a75148b4006a451452c618ccec'"];

【讨论】:

    【解决方案3】:

    试试

    //Case Insensitive
    fetchRequest.predicate=[NSPredicate predicateWithFormat:@"%K = [cd] %@",attributeName,itemValue];
    
    //Case sensitive
    fetchRequest.predicate=[NSPredicate predicateWithFormat:@"%K = %@",attributeName,itemValue];
    

    【讨论】:

    • 1) 请注意,“LIKE”在“*”和“?”中进行通配符比较。有特殊意义! - 2) 对于固定的属性名,不必使用%K
    • @MartinR 感谢您提供的信息 :)。我只是想表明,对于一个属性,占位符需要与 %K 一起使用。如果使用 LIKE 有问题,我们如何进行不区分大小写和变音符号的搜索。
    • 你可以做"my_column ==[cd] %@"
    • @MartinR 太傻了,再次感谢。
    • @Anupdas 不要误会我的意思:这有点像我的头发。在 99% 的情况下,一切都会好起来的,但是是的:使用 %K 使检查 NSPredicates 的所有/每个人的工作变得更容易(并且更健壮)。您根本不必猜测谓词可能意味着什么。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多