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

ios – 使用NSPredicate搜索过滤自定义类数组,第1张

概述我有一个包含自定义类对象的数组,我想基于其中一个类属性是否包含自定义字符串来过滤数组.我有一个方法,传递我想要搜索的属性(列)和它将搜索的字符串(searchString).这是我的代码: NSPredicate *query = [NSPredicate predicateWithFormat:@"%K contains %K", column, searchString];NSMutab 我有一个包含自定义类对象的数组,我想基于其中一个类属性是否包含自定义字符串来过滤数组.我有一个方法,传递我想要搜索的属性(列)和它将搜索的字符串(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;
总结

以上是内存溢出为你收集整理的ios – 使用NSPredicate搜索/过滤自定义类数组全部内容,希望文章能够帮你解决ios – 使用NSPredicate搜索/过滤自定义类数组所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1098537.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-28
下一篇2022-05-28

发表评论

登录后才能评论

评论列表(0条)

    保存