mkto
mkto

Reputation: 4665

need help on a simple predicate to match any word in a string to a property

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 = [query componentsSeparatedByString:@" "];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] ANY %@", words]; 

But it doesnt work. Any guidance? Thanks!

Upvotes: 1

Views: 286

Answers (2)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

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.

Upvotes: 1

Dave DeLong
Dave DeLong

Reputation: 243146

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.

Upvotes: 0

Related Questions