1
votes

I am getting this error when entering a keyword in my searchbox:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "(title CONTAINS[c] 'hj'"

I enter any string ('hj' in this case) followed by an apostrophe (or containing an apostrophe ). No apostrophe - no error.

This is what I did:

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

As I said, the code works if apostrophe character is not included in keyword.

4

4 Answers

12
votes

Sava, try this:

(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];
} 

The main difference from your code is that an apostrophe in the keyword is replaced by backslash-apostrophe.

3
votes

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

0
votes

Try to look at this answer You can do everything as in predicateWithFormat without the quotes

[NSPredicate predicateWithFormat:@"title CONTAINS[c] '%@'", keyword]
0
votes

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];