Search code examples
ioscore-datanspredicate

NSPredicate - Unable to parse the format string


I am trying to write a NSPredicate to fetch rows with my_column value with this string "193e00a75148b4006a451452c618ccec" and I get the below crash.

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "my_column=193e00a75148b4006a451452c618ccec"'

My predicate statement

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@==\"%@\"",attributeName,itemValue]];

also tried this

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@",attributeName,itemValue]];

this

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ = %@",attributeName,itemValue]];

and this

fetchRequest.predicate=[NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@=\"%@\"",attributeName,itemValue]];

Please help.

I found out this, when I was trying with Martin R's answer

fetchRequest.predicate=[NSPredicate predicateWithFormat:@"%@==%@",attributeName,itemValue];

attributeName I pass comes with a ' ' so I took off attributeName and hardcoded it, then it works fine.


Solution

  • Enclose the string in single quotes:

    [NSPredicate predicateWithFormat:@"my_column = '193e00a75148b4006a451452c618ccec'"]
    

    or better, use argument substitution:

    [NSPredicate predicateWithFormat:@"my_column = %@", @"193e00a75148b4006a451452c618ccec"]
    

    The second method avoids problems if the search string contains special characters such as ' or ".

    Remark: Never use stringWithFormat when building predicates. stringWithFormat and predicateWithFormat handle the %K and %@ format differently, so combining these two methods is very error-prone (and unnecessary).