我有一个搜索字段,并且使用以下命令针对 CoreData 触发文本:
produkt.name CONTAINS[cd] %@
但是当用户键入时这会崩溃'
,因为该'
字符弄乱了我的查询:
由于未捕获的异常 NSInvalidArgumentException 导致应用程序终止
原因:无法解析格式字符串 produkt.name CONTAINS[cd]。
CoreData 中没有选项来处理这个问题吗?我无法想象我必须自己逃离它?
我有一个搜索字段,并且使用以下命令针对 CoreData 触发文本:
produkt.name CONTAINS[cd] %@
但是当用户键入时这会崩溃'
,因为该'
字符弄乱了我的查询:
由于未捕获的异常 NSInvalidArgumentException 导致应用程序终止
原因:无法解析格式字符串 produkt.name CONTAINS[cd]。
CoreData 中没有选项来处理这个问题吗?我无法想象我必须自己逃离它?
您不必进行任何字符替换。我猜你正在像这样创建你的谓词:
NSString *s = [NSString stringWithFormat:@"produkt.name CONTAINS[cd] '%@'", term];
NSPredicate *p = [NSPredicate predicateWithFormat:s];
那是不正确的。您需要做的就是:
NSPredicate *p = [NSPredicate predicateWithFormat:@"produkt.name CONTAINS[cd] %@", term];
无论搜索词中的任何单引号等如何,这都将起作用。
您可以用 string 替换该字符串'
,''
例如
string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
我想,它会解决这个问题的。
下面是我尝试过的,并在搜索框中将Oh ' gd '作为字符串传递。
- (void) stringWithPredicateText : (NSString *)predicateText {
if ([predicateText length] >0) {
NSLog(@"predicateText = (%@)",predicateText);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"location contains[cd] %@",predicateText];
NSLog(@"Predicate = <%@>",predicate);
}
}
输出 :
测试[52856:707] predicateText = (Oh ' gd ")
测试[52856:707] 谓词 = (位置 CONTAINS[cd] "Oh ' gd \"")
在这里您可以看到谓词文本和谓词格式正确,它已经处理了 ' 和 " 字符,并且我的应用程序没有崩溃。
If you do not need to search for the '
character, you can simply exclude it from the search field in your text field delegate callback:
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {
if ([string isEqualToString:@"'"]) return NO;
return YES;
}
You could also remove the offending character directly when constructing the predicate.
[NSPredicate predicateWithFormat:@"produkt.name CONTAINS[cd] %@",
[searchString stringByReplacingOccurrencesOfString:@"'" withString:@""]];