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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With