问题描述
我有一个包含自定义类对象的数组,我想基于其中一个类属性是否包含自定义字符串来过滤数组。我有一个方法,传递我想要搜索的属性(列)和它将搜索的字符串(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];
然而,它总是在
抛出异常displayProviders = [[temp filteredArrayUsingPredicate:query] mutableCopy];
说这个类不是密钥值编码兼容的密钥[无论searchString是什么]。
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?
推荐答案
[NSPredicate predicateWithFormat:@"%@ contains %@", column, searchString];
当您使用%@
替换时谓词格式字符串,结果表达式将是常量值。听起来你不想要一个恒定的价值;相反,您希望将属性的名称解释为关键路径。
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:
NSString *column = @"name";
NSString *searchString = @"Dave";
NSPredicate *p = [NSPredicate predicateWithFormat:@"%@ contains %@", column, searchString];
这相当于:
p = [NSPredicate predicateWithFormat:@"'name' contains 'Dave'"];
与以下内容相同:
BOOL contains = [@"name rangeOfString:@"Dave"].location != NSNotFound;
// "contains" will ALWAYS be false
// since the string "name" does not contain "Dave"
这显然不是你想要的。你想要的等价物这个:
That's clearly not what you want. You want the equivalent of this:
p = [NSPredicate predicateWithFormat:@"name contains 'Dave'"];
为了得到这个,你不能使用%@
作为格式说明符。你必须使用%K
。%K
是谓词格式字符串的唯一说明符,它表示替换字符串应解释为键路径(即属性名称),不作为文字字符串。
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.
所以你的代码应该是:
NSPredicate *query = [NSPredicate predicateWithFormat:@"%K contains %@", column, searchString];
使用 @%K包含%K
也不起作用,因为它与以下内容相同:
Using @"%K contains %K"
doesn't work either, because that's the same as:
[NSPredicate predicateWithFormat:@"name contains Dave"]
与以下内容相同:
BOOL contains = [[object name] rangeOfString:[object Dave]].location != NSNotFound;
这篇关于使用NSPredicate搜索/过滤自定义类数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!