ios – 使用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 = [[temp filteredArrayUsingPredicate:query] mutableCopy];
说这个类不是密钥值编码兼容的密钥[无论searchString是什么].

我有什么想法我做错了吗?

解决方法

[NSPredicate predicateWithFormat:@"%@ contains %@",searchString];

在谓词格式字符串中使用%@ substitution时,生成的表达式将是常量值.听起来你不想要一个恒定的价值;相反,您希望将属性的名称解释为键路径.

换句话说,如果你这样做:

NSString *column = @"name";
NSString *searchString = @"Dave";
NSPredicate *p = [NSPredicate predicateWithFormat:@"%@ contains %@",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"

这显然不是你想要的.你想要相当于这个:

p = [NSPredicate predicateWithFormat:@"name contains 'Dave'"];

为了实现这一点,您不能使用%@作为格式说明符.你必须使用%K. %K是谓词格式字符串唯一的说明符,它表示替换字符串应该被解释为键路径(即属性的名称),而不是文字字符串.

所以你的代码应该是:

NSPredicate *query = [NSPredicate predicateWithFormat:@"%K contains %@",searchString];

使用@“%K包含%K”也不起作用,因为它与以下内容相同:

[NSPredicate predicateWithFormat:@"name contains Dave"]

这与以下相同:

BOOL contains = [[object name] rangeOfString:[object Dave]].location != NSNotFound;

相关文章

UITabBarController 是 iOS 中用于管理和显示选项卡界面的一...
UITableView的重用机制避免了频繁创建和销毁单元格的开销,使...
Objective-C中,类的实例变量(instance variables)和属性(...
从内存管理的角度来看,block可以作为方法的传入参数是因为b...
WKWebView 是 iOS 开发中用于显示网页内容的组件,它是在 iO...
OC中常用的多线程编程技术: 1. NSThread NSThread是Objecti...