1

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!

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498
mkto
  • 4,584
  • 5
  • 41
  • 65
  • i know my another option is to do sth like this: NSMutableArray *subPredicates = [[NSMutableArray alloc] init]; for(NSString *word in words) { NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name CONTAINS[cd] %@", word]; [subPredicates addObject:predicate]; } predicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates]; but i hope to see if i can use the keyword ANY which i m not familiar with in this scenario – mkto Jun 28 '11 at 03:07

2 Answers2

1

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.

Community
  • 1
  • 1
Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
  • 1
    Yeah, `SUBQUERY` is one of those weirder things of `NSPredicate`. Once you get how it works, you can't help but think of a way to use it in almost every situation. – Dave DeLong Jun 28 '11 at 03:57
0

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.

Dave DeLong
  • 242,470
  • 58
  • 448
  • 498