Reputation: 185
I have an NSArray of, say Article objects. Article object contains another NSArray of tags to the article.
So I want to find articles that contain a set of tags like [iphone, apple, music].
In SQL it would be like: WHERE tags IN ('iphone', 'apple', 'music')
.
So far I have only found how to use NSPredicate to finds elements by single value:
NSArray *filteredItems = [article filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:@"tag == %@", @"iphone"]];
Is there a way to do what I need to?
Upvotes: 0
Views: 485
Reputation: 5240
You can use NSCompoundPredicate
to merge together various NSPredicate
objects like this:
NSMutableArray *predicates = [NSMutableArray array];
[predicates addObject:[NSPredicate predicateWithFormat:@"tag == %@", @"iphone"]]];
[predicates addObject:[NSPredicate predicateWithFormat:@"tag == %@", @"apple"]]];
[predicates addObject:[NSPredicate predicateWithFormat:@"tag == %@", @"music"]]];
//Create a predicate using AND
NSPredicate *compoundANDpred = [NSCompoundPredicate andPredicateWithSubpredicates:predicates];
//Create a predicate using OR
NSPredicate *compoundORpred = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];
or you could use a predicate with ANY and IN, as outlined in some of the other answers.
Upvotes: 1
Reputation: 258
This can also be done like this
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"tag == %@", @[@"iphone", @"apple", @"music"]];
NSArray *result = [dataArray filterUsingPredicate:predicate];
Upvotes: 0
Reputation: 654
You can use ANY and IN clause
NSArray *tags = ...;
[NSPredicate predicateWithFormat:@"ANY tags.name IN %@",tags]
Upvotes: 2
Reputation: 2124
You wan use the predicate like below
NSPredicate *template = [NSPredicate predicateWithFormat:@"tag == %@ OR tag == %@ OR tag == %@",@"iphone",@"apple",@"music"];
Upvotes: 0