问题
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.
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.
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.
How should I setup my predicateWithFormat statement?
This wont' work cuz it's doing the opposite:
NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"substring LIKE[c] %@", @"ABCDEF"];
Thanks all!
回答1:
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.
回答2:
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".
来源:https://stackoverflow.com/questions/10941811/a-reverse-kind-of-string-compare-using-nspredicate