NSPredicate predicateWithFormat:(NSString *)不一致? [英] NSPredicate predicateWithFormat:(NSString*) inconsistency?

查看:114
本文介绍了NSPredicate predicateWithFormat:(NSString *)不一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在根据用户输入过滤我的NSMutableDictionary时,我创建了以下代码:

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"通过以下定义传递到方法中:

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

(NSString*) searchString

但这导致以下异常:

... raised [valueForUndefinedKey:]:此类是 不符合该键的键值编码...

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

原来的解决方法是:

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

我不明白的是,后者为何起作用,而前者引发了例外.我已经阅读了键值编码,但我不明白在这里如何应用. (即仅通过更改NSPredicate的定义方式)有人可以启发我吗?

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?

更新: 为了回应jtbandes的评论,我继续创建了一个TestApp项目来演示此问题. http://dl.dropbox.com/u/401317/TestApp1.tar.gz

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

推荐答案

答案是

字符串常量必须在表达式中加引号-单引号和双引号均可接受,... 如果您使用%@ ...进行变量替换,则会自动为您添加引号 .如果您在格式字符串中使用字符串常量,则您必须自己用引号

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

[我的重点]

predicateWithFormat为您添加引号,但stringWithFormat则不.如果您这样做,第一个示例可能会起作用:

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

这篇关于NSPredicate predicateWithFormat:(NSString *)不一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆