Forrest
Forrest

Reputation: 620

Core Data Predicate - Check if any element in array matches any element in another array

I'm trying to use a predicate to filter objects where an intersection exists between two arrays.

The NSManagedObject has an array(Of Strings) attribute named "transmissions". And there is another array(Of Strings) that will contain words to filter by, named "filters".

I'm not sure how to find if any elements in "transmissions" match any element in "filters".

I've tried

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF.transmission in[c] %@",transmissions];

or

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY transmission in[c] %@",transmissions];

However, core data fetches no results where there should be some.

Upvotes: 2

Views: 2942

Answers (2)

Zack Brown
Zack Brown

Reputation: 6028

You can use the keyword CONTAINS to check an object exists in a collection.

[NSPredicate predicateWithFormat:@"favouriteFilms CONTAINS %@", film]

I believe the same thing can be achieved with IN by switching the LHS and RHS of the predicate. I have only successfully implemented this functionality using CONTAINS however.

Upvotes: 0

Hamza Azad
Hamza Azad

Reputation: 2637

Try this.

NSPredicate *predicate = nil;
NSMutableArray *predicates = [NSMutableArray new];
for (NSString *transmission in transmissions) {
    [predicates addObject:[NSPredicate predicateWithFormat:@"transmission == %@", transmission]];
}
if (predicates.count > 0)
    predicate = [NSCompoundPredicate orPredicateWithSubpredicates:predicates];

// make fetch request using 'predicate'

Upvotes: 1

Related Questions