1

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.

vascowhite
  • 18,120
  • 9
  • 61
  • 77
John Smith
  • 2,012
  • 1
  • 21
  • 33

4 Answers4

12

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.

Alexey Golikov
  • 652
  • 8
  • 19
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

anoop4real
  • 7,598
  • 4
  • 53
  • 56
0

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

[NSPredicate predicateWithFormat:@"title CONTAINS[c] '%@'", keyword]
Community
  • 1
  • 1
rano
  • 5,616
  • 4
  • 40
  • 66
  • yep, but try to do that with the single predicateWithFormat, no need to expand it with a stringWithFormat I guess – rano Nov 05 '12 at 11:14
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];
jwhat
  • 2,042
  • 23
  • 29