Let's say i want to let user search for my objects using a name property of the objects.
I have no problem if the user only enters one word: e.g: facial
My predicate will be:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", word];
But what if user enter more than one word separated by space? I want to do sth like:
NSArray *words = [que开发者_如何学Gory componentsSeparatedByString:@" "];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] ANY %@", words];
But it doesnt work. Any guidance? Thanks!
Another way of doing this (and I just learnt this myself as a result of your question) is to use subqueries. Check this SO question
for more details. You can use subqueries in the following manner –
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(%@, $str, SELF CONTAINS[cd] $str).@count != 0", words];
NSLog(@"%@", [array filteredArrayUsingPredicate:predicate]);
This seems to work as I've tested it myself but this could also be the arcane & obscure way that Dave has mentioned as it finds no mention in the Predicate Programming Guide.
The format for a SUBQUERY
can be found here
. It's the same link that you will find in the question linked earlier.
As you mentioned (correctly) in the comment, you can do this by building a compound predicate predicate, although you'll want to use orPredicateWithSubpredicates
, and not the and
variant.
That really is the best way to do this. There are others, but they rely on more arcane and obscure uses of NSPredicate
, and I really recommend going with the build-a-compound-predicate route.
精彩评论