使用NSPredicatesearch/过滤自定义类数组

我有一个包含自定义类的对象的数组,我想过滤的数组,如果其中一个类属性包含自定义string。 我有一个方法传递了我想要search的属性(列)和它将search的string(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]上引发exception; 说这个类不是关键的值编码的密钥[无论searchString是]。

任何想法我做错了什么?

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

在谓词格式string中使用%@replace时,得到的expression式将是一个常量值 。 这听起来像你不想要一个恒定的价值; 相反,您希望将属性的名称解释为关键path。

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

 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" 

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

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

为了得到这个,你不能使用%@作为格式说明符。 您必须改用%K%K是谓词格式string唯一的说明符,它表示被replace的string应该被解释为键path(即属性的名称),而不是作为文字string。

所以你的代码应该是:

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

使用@"%K contains %K"也不起作用,因为这与以下内容相同:

 [NSPredicate predicateWithFormat:@"name contains Dave"] 

这是一样的:

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

在谓词string中将%Kreplace为%@

 @"%@ contains %@", column, searchString 

这对我有用

 [self.array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"name contains 'Dave'"]];