A reverse kind of string compare using NSPredicate

痴心易碎 提交于 2019-12-05 10:42:41

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.

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

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

I think this will work:

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

You would use it like this in core data:

-(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);
}

In this example, "desc" is an attribute of the entity "Expense". This correctly retrieves only the rows where "desc" is a substring of "ABCDEF".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!