【问题标题】:NSPredicate Single Quote IssueNSPredicate 单引号问题
【发布时间】:2013-01-02 02:23:59
【问题描述】:

现在我在 NSPredicate 中遇到单引号 ( ' ) 问题。

这是我的查询:

 NSPredicate *query = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"s_name='%@' AND s_regno=%d",Name,[RegNo intValue]]];

当我使用名称“John”进行过滤时,一切正常,完全没有错误。但我用的名字是“Mary ' Monny”。有错误。

我怀疑这是因为单引号。请帮我解决这个问题。

谢谢

【问题讨论】:

    标签: objective-c xcode4 nspredicate


    【解决方案1】:

    作为一种快速修复,您根本不需要NSString 部分。这个替换是predicateWithFormat: 方法的重点!只需使用:

    NSPredicate *query = [NSPredicate predicateWithFormat:@"s_name == %@ AND s_regno == %d", Name, [RegNo intValue]];
    

    我喜欢完全避免使用格式字符串,而是在代码中构建谓词。

    NSPredicate *nameQuery =
    [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"s_name"]
                                       rightExpression:[NSExpression expressionForConstantValue:Name]
                                              modifier:NSDirectPredicateModifier
                                                  type:NSLikePredicateOperatorType
                                               options:NSCaseInsensitivePredicateOption|NSDiacriticInsensitivePredicateOption];
    
    NSPredicate *regNoQuery =
    [NSComparisonPredicate predicateWithLeftExpression:[NSExpression expressionForKeyPath:@"s_regno"]
                                       rightExpression:[NSExpression expressionForConstantValue:RegNo]
                                              modifier:NSDirectPredicateModifier
                                                  type:NSEqualToPredicateOperatorType
                                               options:0];
    
    NSPredicate *query = [NSCompoundPredicate andPredicateWithSubpredicates:@[nameQuery,regNoQuery]];
    

    请注意,我添加了NSCaseInsensitivePredicateOption|NSDiacriticInsensitivePredicateOption 以对名称进行不区分大小写和变音符号的比较,如s_name like[cd] %@。如果不需要,当然可以使用type:NSEqualToPredicateOperatorTypeoptions:0

    【讨论】:

      【解决方案2】:

      如果 name = @"Bell's",你可以尝试这样做谓词:

      NSPredicate *query = [NSPredicate predicateWithFormat:@"name == \"%@\"", name];  
      

      只需将标准单引号替换为双引号即可。

      【讨论】:

      • 如果你的输入字符串有双引号,那是什么?
      猜你喜欢
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 2011-01-03
      • 1970-01-01
      • 1970-01-01
      • 2019-05-05
      相关资源
      最近更新 更多