NSPredicate对一对多关系的大小写不敏感匹配 [英] NSPredicate case-insensitive matching on to-many relationship

查看:106
本文介绍了NSPredicate对一对多关系的大小写不敏感匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一个搜索字段,用户可以在其中键入字符串来过滤视图中显示的项目。每个显示的对象都有一个关键字多对一关系,我想能够根据对象的关键字过滤对象。每个关键字对象都有一个 name 属性,所以我设置了一个NSPredicate来进行过滤,看起来像这样:

  NSPredicate * predicate = [NSPredicate predicateWithFormat:@keywords.name CONTAINS%@,self.searchString]; 

这样有效,但问题是搜索区分大小写,大写字母,但用户键入所有小写,没有找到匹配。我尝试了以下修改:

  NSPredicate * predicate = [NSPredicate predicateWithFormat:@keywords.name CONTAINS [c] @,self.searchString]; 

但这不会对匹配的大小写敏感性产生任何影响。有没有办法做这种不区分大小写的匹配只使用一个简单的谓词?或者我需要在关键字类上实现某种自定义访问器。写一个 lowercaseName 方法,并匹配搜索字符串的小写版本?



附录:
在进一步探索之后,添加自定义访问器的解决方法可以手动使用NSPredicate,但是当使用NSFetchRequest与Core Data时不起作用,只有在查询Core Data模型中定义的属性时才会工作。

解决方案

如果我正确理解你,只要任何关键词匹配搜索字符串,你的谓词都是真的。为此,您需要使用ANY关键字进行测试,如下所示:

  [NSPredicate predicateWithFormat:@ANY keywords.name CONTAINS [c ]%@,...] 

这将搜索关键字,并返回true如果任何这些关键字name包含您的搜索字符串。 p>

I am implementing a search field where the user can type in a string to filter the items displayed in a view. Each object being displayed has a keywords to-many relationship, and I would like to be able to filter the objects based on their keywords. Each keyword object has a name property, so I've set up an NSPredicate to do the filtering that looks like this:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"keywords.name CONTAINS %@", self.searchString];

This works, but the problem is that the search is case-sensitive, so if the keyword has a capital letter but the user types in all lowercase, no matches are found. I've tried the following modification:

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"keywords.name CONTAINS[c] %@", self.searchString];

But that doesn't make any difference in the case sensitivity of the matching. Is there a way to do this case-insensitive matching using just a plain predicate? Or will I need to implement some sort of custom accessor on the keyword class, e.g. write a lowercaseName method and match against a lowercased version of the search string instead?

Addendum: After further exploration, the workaround of adding a custom accessor works OK for manual use of NSPredicate, but does not work at all when using NSFetchRequest with Core Data, which only works when querying attributes defined in the Core Data model.

解决方案

If I understand you correctly, you want your predicate to be true whenever any keywords name matches the search string. For this you need to test with the ANY keyword like this:

[NSPredicate predicateWithFormat:@"ANY keywords.name CONTAINS[c] %@", ...];

This will search the keywords and return true if any of those keywords name contains your search string.

这篇关于NSPredicate对一对多关系的大小写不敏感匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆