使用 NSPredicate 搜索/过滤自定义类数组
我有一个包含自定义类的对象的数组,我想根据类属性之一是否包含自定义字符串来过滤该数组。我有一个方法传递了我想要搜索的属性(列)和它将搜索的字符串(searchString)。这是我的代码:
NSPredicate *query = [NSPredicate predicateWithFormat:@"%K contains %K", column, searchString];
NSMutableArray *temp = [displayProviders mutableCopy];
[displayProviders release];
displayProviders = [[temp filteredArrayUsingPredicate:query] mutableCopy];
[temp release];
但是,它总是抛出异常 displayProviders = [[tempfilteredArrayUsingPredicate:query]mutableCopy]; 说这个类不符合键值编码[无论 searchString 是什么]。
有什么想法我做错了吗?
I have a array that contains objects of a custom class, and I would like to filter the array based on if one of the classes attributes contains a custom string. I have a method that is passed the attribute that I want to be searched (column) and the string that it will search for (searchString). Here is the code I have:
NSPredicate *query = [NSPredicate predicateWithFormat:@"%K contains %K", column, searchString];
NSMutableArray *temp = [displayProviders mutableCopy];
[displayProviders release];
displayProviders = [[temp filteredArrayUsingPredicate:query] mutableCopy];
[temp release];
However, it always throws an exception on
displayProviders = [[temp filteredArrayUsingPredicate:query] mutableCopy];
saying this class is not key value coding-compliant for the key [whatever searchString is].
Any ideas what I am doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您在谓词格式字符串中使用
%@
替换时,生成的表达式将是常量值。听起来你不想要一个恒定的值;相反,您希望将属性名称解释为关键路径。换句话说,如果你这样做:
这将相当于:
这与:
这显然不是你想要的。您想要与此等效的内容:
为了获得此效果,您不能使用
%@
作为格式说明符。您必须使用%K
来代替。%K
是谓词格式字符串特有的说明符,它意味着替换的字符串应被解释为键路径(即属性的名称),而不作为文字字符串。因此,您的代码应该是:
使用
@"%K contains %K"
也不起作用,因为这与:与以下相同:
When you use the
%@
substitution in a predicate format string, the resulting expression will be a constant value. It sounds like you don't want a constant value; rather, you want the name of an attribute to be interpreted as a key path.In other words, if you're doing this:
That is going to be the equivalent to:
Which is the same as:
That's clearly not what you want. You want the equivalent of this:
In order to get this, you can't use
%@
as the format specifier. You have to use%K
instead.%K
is a specifier unique to predicate format strings, and it means that the substituted string should be interpreted as a key path (i.e., name of a property), and not as a literal string.So your code should instead be:
Using
@"%K contains %K"
doesn't work either, because that's the same as:Which is the same as:
将谓词字符串中的
%K
替换为%@
,Replace
%K
to%@
in your predicate string,这对我有用
This Works for me