Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate predicateWithFormat:(NSString*) inconsistency?

Tags:

objective-c

While working on filtering my NSMutableDictionary based on user input, I created the following code:

NSString *predicateString = [NSString stringWithFormat:@"SELF beginsWith[cd] %@", searchString];
NSPredicate *pred = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredKeys = [[myMutableDictionary allKeys] filteredArrayUsingPredicate:pred]; 

"searchString" is passed into the method with this definition:

(NSString*) searchString

This however resulted in the following exception:

...raised [ valueForUndefinedKey:]: this class is not key value coding-compliant for the key...

The fix turned out to be:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF beginsWith[cd] %@", searchString];
NSArray *filteredKeys = [[myMutableDictionary allKeys] filteredArrayUsingPredicate:pred]; 

What I don't understand, is why the latter worked, and the former threw the exception. I have read a little bit on key value coding, but I don't understand how it applies here. (i.e. only by changing how the NSPredicate is defined) Can someone enlighten me?

Update: In response to jtbandes comment, I went ahead and created a TestApp project to demo this problem. http://dl.dropbox.com/u/401317/TestApp1.tar.gz

like image 583
yanigisawa Avatar asked Jul 17 '11 20:07

yanigisawa


1 Answers

The answer is in the predicate programming guide.

String constants must be quoted within the expression—single and double quotes are both acceptable, ... If you use variable substitution using %@ ..., the quotation marks are added for you automatically. If you use string constants within your format string, you must quote them yourself

[my emphasis]

predicateWithFormat puts the quotes in for you, but stringWithFormat doesn't. Your first example would probably work if you did this:

NSString *predicateString = [NSString stringWithFormat:@"SELF beginsWith[cd] '%@'", searchString];
//                                                                           ^  ^ single or double quotes
like image 131
JeremyP Avatar answered Sep 23 '22 05:09

JeremyP