使用NSPredicate进行反向string比较

我一直在寻找这个答案在互联网上,但迄今没有运气。 所以我需要咨询这里的聪明人和好人。 这是我第一次在这里问一个问题,所以我希望我这样做是正确的,而不是重复这个问题。

对于我所看到的所有示例,searchstring是存储在Core Data中的子string。 另一方面,我想达到以下目的:

存储在核心数据中的string实际上是子string。 我想通过获取所有具有属于所提供的searchstring的子string的核心数据行来进行search。

例如:在核心数据中,我有“AB”,“BC”,“ABC”,“ABCDEF”,“GH”,“ABA”在应用程序中,通过提供超级​​string“ABCDEF” ,结果将返回“AB”,“BC”,“ABC”,“ABCDEF”而不是“GH”,“ABA”,因为这两个子串不属于超级串。

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

这不会'工作因为它正在做相反的:

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

谢谢大家!

CONTAINS的反向将不起作用。 此外,您将无法使用LIKE因为您必须将正在search的属性转换为通配符string。

要走的路是使用MATCHES因为您可以使用正则expression式。 首先,通过在每个字母后添加*来将searchstring转换为正则expression式。 然后形成谓词。

此解决scheme已经过testing,可以与您的示例一起使用

 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]; 

where谓词中的stringAttribute是您的托pipe对象的NSString属性的名称。

我认为这将工作:

 NSPredicate *pred = [NSPredicate predicateWithFormat:@"%@ contains self",@"ABCDEF"]; 

你可以在核心数据中这样使用它:

 -(IBAction)doFetch:(id)sender { NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.entity = [NSEntityDescription entityForName:@"Expense" inManagedObjectContext:self.managedObjectContext]; request.predicate = [NSPredicate predicateWithFormat:@"%@ contains desc",@"ABCDEF"]; NSArray *answer = [self.managedObjectContext executeFetchRequest:request error:nil]; NSLog(@"%@",answer); } 

在这个例子中,“desc”是实体“Expense”的一个属性。 这正确地只检索“desc”是“ABCDEF”的子string的行。