在根据用户输入过滤我的NSMutableDictionary时,我创建了以下代码:
NSString *predicateString = [NSString stringWithFormat:@"SELF beginsWith[cd] %@", searchString];
NSPredicate *pred = [NSPredicate predicateWithFormat:predicateString];
NSArray *filteredKeys = [[myMutableDictionary allKeys] filteredArrayUsingPredicate:pred];
Run Code Online (Sandbox Code Playgroud)
使用此定义将"searchString"传递给方法:
(NSString*) searchString
Run Code Online (Sandbox Code Playgroud)
然而,这导致以下异常:
... raise [valueForUndefinedKey:]:此类不是密钥值编码兼容的密钥...
修复原来是:
NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF beginsWith[cd] %@", searchString];
NSArray *filteredKeys = [[myMutableDictionary allKeys] filteredArrayUsingPredicate:pred];
Run Code Online (Sandbox Code Playgroud)
我不明白的是,为什么后者有效,前者抛出异常.我已经阅读了一些关于键值编码的内容,但我不明白它在这里是如何应用的.(即仅通过改变NSPredicate的定义方式)有人可以启发我吗?
更新: 为了回应jtbandes的评论,我继续创建了一个TestApp项目来演示这个问题.http://dl.dropbox.com/u/401317/TestApp1.tar.gz
Jer*_*myP 17
答案在谓词编程指南中.
字符串常量必须在表达式中引用 - 单引号和双引号都是可接受的,... 如果使用%@ ...使用变量替换,则会自动为您添加引号.如果在格式字符串中使用字符串常量,则必须自己引用它们
[我的重点]
predicateWithFormat把报价给你,但stringWithFormat不是.如果您这样做,您的第一个示例可能会有效:
NSString *predicateString = [NSString stringWithFormat:@"SELF beginsWith[cd] '%@'", searchString];
// ^ ^ single or double quotes
Run Code Online (Sandbox Code Playgroud)