Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Core Data predicate to test that a relation contains all given objects?

Setup:

I have a Core Data object A that has a to-many relation to B. Call the relation "items". So, a.items returns all B-s associated with A.

Now, I have a manually composed NSSet "itemSet" of B objects.

I want to do the following:

return all A objects whose "items" relation exactly matches itemSet

How do I construct a predicate for that? I’ve tried this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"(ALL items in %@)", itemSet];

But that just gives me Unsupported predicate (null).

This:

NSPredicate *predicate = [NSPredicate predicateWithFormat:
                          @"(items in %@)", itemSet];

tells me unimplemented SQL generation for predicate. Interesting, but not helpful.

So what’s the right way to filter the relation with a set?

like image 411
Jaanus Avatar asked Oct 26 '12 10:10

Jaanus


1 Answers

The following predicate could work:

[NSPredicate predicateWithFormat:@"(items.@count == %d) AND (SUBQUERY(items, $x, $x IN %@).@count == %d)",
                      itemSet.count, itemSet, itemSet.count];

The predicate checks first that the number of items is equal to the size of the given itemSet, and then checks that the number of items which are member of itemSet is also equal to the size of itemSet. If both are true, then items must be equal to itemSet.

like image 102
Martin R Avatar answered Oct 20 '22 03:10

Martin R