0
votes

I have a search field and the text is fired against CoreData using:

produkt.name CONTAINS[cd] %@

but this crashes when the user types ', because the ' character messes up my query:

Terminating app due to uncaught exception NSInvalidArgumentException
Reason: Unable to parse the format string produkt.name CONTAINS[cd].

Isn't there an option in CoreData to handle that? I can't imagine that I have to escape it by myself?

4
It should be no problem to search for '. Please show the code how you create the predicate. - Martin R

4 Answers

2
votes

You should not have to do any substitution of characters whatsoever. I'm guessing that you're creating your predicate like this:

NSString *s = [NSString stringWithFormat:@"produkt.name CONTAINS[cd] '%@'", term];
NSPredicate *p = [NSPredicate predicateWithFormat:s];

That would be incorrect. All you need to do is this:

NSPredicate *p = [NSPredicate predicateWithFormat:@"produkt.name CONTAINS[cd] %@", term];

That will work regardless of any single quotes, etc in the search term.

0
votes

i think ,it will take care of that .

below is what i tried is and passed Oh ' gd " as string in search Box.

- (void) stringWithPredicateText : (NSString *)predicateText {

    if ([predicateText length] >0) {
        NSLog(@"predicateText = (%@)",predicateText);
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"location contains[cd] %@",predicateText];
        NSLog(@"Predicate = <%@>",predicate);
    }   

}

output :

Test[52856:707] predicateText = (Oh ' gd ")

Test[52856:707] Predicate = (location CONTAINS[cd] "Oh ' gd \"")

Here You can see predicate text and Predicate are correctly formed, its already taking care of ' and " character , and my app does not crash .

0
votes

You can replace that string ' with string '', like

string = [string stringByReplacingOccurrencesOfString:@"'" withString:@"''"];
-1
votes

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:@""]];