NSPredicate 问题

Posted

技术标签:

【中文标题】NSPredicate 问题【英文标题】:NSPredicate problem 【发布时间】:2011-09-14 08:00:15 【问题描述】:

我正在尝试使用 NSPredicate 搜索对象数组。这些对象有许多我想要过滤的 NSString 属性。

我有以下代码来做过滤:

NSString *predicateString = [NSString stringWithFormat:@"name like[c] %@",self.textFieldOutlet.text];
NSPredicate *searchPredicate = [NSPredicate predicateWithFormat:predicateString];
NSArray *results = [[MySingleton sharedMySingleton].cardArray filteredArrayUsingPredicate:searchPredicate];

但我收到以下错误:

WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: <NSUnknownKeyException> [<CardObject 0x14a530> valueForUndefinedKey:]: this class is not key value coding-compliant for the key test.

如果我在%@ 周围加上单引号,它会起作用,但前提是输入的文本与 name 键的值完全相同,而不是“像”值。因此不是很有用。我一定是对谓词字符串做错了什么,有人可以建议吗?

提前致谢!

【问题讨论】:

你会发布要存储在 predicateString 中的值吗? 错误看起来无关。您能否仔细检查该应用是否仅在您插入单引号时才有效? 抱歉耽搁了各位。 @iApple predicateString = name like[c] test. @xj1200 我可以确认,当我包含单引号时,谓词只会返回一个值。它只在字符串完全匹配时返回一些东西:( 【参考方案1】:

显然,错误表明您的对象不符合键值对。 尝试改用 NSDictionary

【讨论】:

【参考方案2】:

错误表明您的 CardObjects 不支持 KVO 的属性“测试”。

但是,您的谓词只是要求比较 name 属性,所以看起来这个谓词不是您的 web 视图崩溃的原因。

您能否将您的 webView:shouldInsertText:replacingDOMRange:givenAction: 方法的内容添加到问题中,因为这是错误发生的地方。

我认为更改谓词会更改此方法后面的代码流,这就是错误所在(但没有看到您的其余代码,这有点猜测!)。

【讨论】:

您好,院长,感谢您的回答。我只是注意到错误中有一个 webview,我不知道为什么会这样,因为代码不是从 web view 调用的,而是一个普通的视图控制器?!抱歉错过了,我想我已经盯着同一个代码太久了!【参考方案3】:

好的,我仍然不知道为什么会收到 NSPredicate 的 webview 错误。但我已经使用以下谓词字符串解决了这个问题:

(name like[cd] '*%@*')

【讨论】:

以上是关于NSPredicate 问题的主要内容,如果未能解决你的问题,请参考以下文章

NSPredicate 问题

子查询中的 NSPredicate

NSPredicate 格式问题

NSPredicate 和 NSArray

如何向 NSPredicate 添加连接

NSPredicate 字符串