使用 NSPredicate 搜索/过滤自定义类数组 [英] Searching/Filtering a custom class array with a NSPredicate
问题描述
我有一个包含自定义类对象的数组,我想根据类属性之一是否包含自定义字符串来过滤该数组.我有一个方法,它传递了我想要搜索的属性(列)和它将搜索的字符串(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].
知道我做错了什么吗?
推荐答案
[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 contains %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 搜索/过滤自定义类数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!