一种反向类型的字符串比较使用NSPredicate [英] A reverse kind of string compare using NSPredicate

查看:113
本文介绍了一种反向类型的字符串比较使用NSPredicate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在网上搜索这个答案,但到目前为止没有运气。所以我需要在这里咨询聪明和好人。这是我第一次在这里提问,所以我希望我这样做,不要重复这个问题。

I've been searching for this answer all over internet but so far no luck. So I need to consult the smart and nice people here. This is my first time asking a question here, so I hope I am doing this right and not repeating the question.

对于我看到的所有示例,它是搜索字符串这是Core Data中存储的子字符串。另一方面,我想实现以下:

For all the examples I saw, it's the search string that is a substring of what's stored in the Core Data. On the other hand, I want to achieve the following:

核心数据中存储的字符串实际上是子字符串。我想通过获取具有子字符串的所有核心数据行属于所提供的搜索字符串来进行搜索。

The strings stored in core data are actually sub-strings. I want to do a search by getting all core data rows that have substrings belong to the provided search string.

例如:
在核心数据中, AB,BC,ABC,ABCDEF,GH,ABA
在应用程序中,我通过提供超级​​字符串:ABCDEF AB,BC,ABC,ABCDEF而不是GH,ABA,因为这两个子字符串不属于超串。

For ex: In core data, I have "AB", "BC","ABC","ABCDEF","GH", "ABA" And in the app I do a search by providing the super-string: "ABCDEF", the result will return "AB","BC","ABC","ABCDEF" but not "GH", "ABA" because these two sub-strings don't belong to the super-string.

我应该如何设置我的predicateWithFormat语句?

How should I setup my predicateWithFormat statement?

这不会工作正好相反:

NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"substring LIKE[c] %@", @"ABCDEF"];

谢谢所有!

推荐答案

CONTAINS 的反向无效。此外,您将无法使用 LIKE ,因为您必须获取您正在搜索的属性,并将其转换为通配符字符串。

The reverse of CONTAINS will not work. Also, you will not be able to use LIKE because you would have to take the attribute you are searching and transform it into a wildcard string.

使用 MATCHES 的方法是可以使用正则表达式。首先,通过在每个字母之后附加 * ,将搜索字符串转换为正则表达式。然后形成谓词。

The way to go is to use MATCHES because you can use regular expressions. First, transform your search string into a regex by affixing a * after each letter. Then form the predicate.

此解决方案已经过测试,可用于您的示例。

This solution has been tested to work with your example.

NSString *string= @"ABCDEF";
NSMutableString *new = [NSMutableString string];
for (int i=0; i<string.length; i++) {
    [new appendFormat:@"%c*", [string characterAtIndex:i]]; 
}
// new is now @"A*B*C*D*E*F*";
fetchRequest.predicate = [NSPredicate predicateWithFormat:
                          @"stringAttribute matches %@", new];

其中 stringAttribute 您的托管对象的 NSString 属性。

where stringAttribute in the predicate is the name of your NSString attribute of your managed object.

这篇关于一种反向类型的字符串比较使用NSPredicate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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