NSPredicate - Unable to parse the format string

Satheesh picture Satheesh · May 3, 2013 · Viewed 23.7k times · Source

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.

Answer

Martin R picture Martin R · May 3, 2013

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).