NSPredicate - Unable to parse the format string [d

2020-06-07 05:19发布

问题:

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.

回答1:

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



回答2:

I think you have missed '' when checking for equality,

now try,

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


回答3:

Try

//Case Insensitive
fetchRequest.predicate=[NSPredicate predicateWithFormat:@"%K = [cd] %@",attributeName,itemValue];

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