gpt4 book ai didi

ios - 使用 NSPredicate 搜索/过滤自定义类数组

转载 作者:可可西里 更新时间:2023-11-01 03:36:36 25 4
gpt4 key购买 nike

我有一个包含自定义类对象的数组,我想根据其中一个类属性是否包含自定义字符串来过滤该数组。我有一个方法传递了我想要搜索的属性(列)和它将搜索的字符串(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];说这个类不符合键的键值编码 [whatever searchString is]。

知道我做错了什么吗?

最佳答案

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

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

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

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 是谓词格式字符串特有的说明符,它意味着被替换的字符串应该被解释为关键路径(即属性名称),不是作为文字字符串。

所以你的代码应该是:

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;

关于ios - 使用 NSPredicate 搜索/过滤自定义类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7207050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com