现在我在 NSPredicate 中遇到单引号 ( ' ) 问题。
这是我的查询:
NSPredicate *query = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"s_name='%@' AND s_regno=%d",Name,[RegNo intValue]]];
当我使用名称“John”进行过滤时,一切正常,完全没有错误。但我使用的名字是“Mary ' Monny”。有错误。
我怀疑这是因为单引号。请帮我解决这个问题。
谢谢
最佳答案
作为快速修复,您根本不需要 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:NSEqualToPredicateOperatorType
和 options:0
。
关于objective-c - NSPredicate 单引号问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14116217/