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
The answer is in the predicate programming guide.
[my emphasis]
predicateWithFormatputs the quotes in for you, butstringWithFormatdoesn’t. Your first example would probably work if you did this: