1

在搜索框中输入关键字时出现此错误:

由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'无法解析格式字符串“(title CONTAINS [c]'hj'”

我输入任何字符串(在这种情况下为“hj”),后跟一个撇号(或包含一个撇号)。没有撇号 - 没有错误。

这就是我所做的:

(void)filter:(NSString*)keyword{
    NSString* predicateString = [NSString stringWithFormat:@"(title CONTAINS[c] '%@')", keyword];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
    self.filteredArray = [self.initialArray filteredArrayUsingPredicate:predicate];
} 

正如我所说,如果关键字中不包含撇号字符,则代码有效。

4

4 回答 4

12

萨瓦,试试这个:

(void)filter:(NSString*)keyword{
    NSString *keywordWithBackslashedApostrophes = [keyword stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"];
    NSString* predicateString = [NSString stringWithFormat:@"title CONTAINS[c] '%@'", keywordWithBackslashedApostrophes];
    NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateString];
    self.filteredArray = [self.initialArray filteredArrayUsingPredicate:predicate];
} 

与您的代码的主要区别在于关键字中的撇号被反斜杠撇号替换。

于 2012-11-08T13:51:21.280 回答
3

I too had problems with this predicate filter I had customer names like O'Connor and the query used to fail. The solution suggested by Alexey Golikov works fine, but I would like to know if there is any NSPredicate class level fix for this. String operations are always a costly thing you may not want to do it until necessary.

-anoop

于 2013-06-11T07:38:40.133 回答
0

试着看看这个答案predicateWithFormat你可以在没有引号的情况下 做所有事情

[NSPredicate predicateWithFormat:@"title CONTAINS[c] '%@'", keyword]
于 2012-11-05T11:10:19.933 回答
0

The problem is creating an NSString when you don't need to do that. Notice here that we don't need an NSString variable, and we removed the apostrophes from %@.

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(title CONTAINS[c] %@)", keyword];
于 2014-11-26T00:21:49.310 回答