How to use the "ALL" aggregate operation in a NSPredicate to filter a CoreData-based collection

Stian Høiland picture Stian Høiland · Mar 14, 2011 · Viewed 8.4k times · Source

Based on the data model below

dataModel

And based on user input I create a NSSet of managedObjects of entity Tag called selectedTags.


My problem:

[NSPredicate predicateWithFormat:@"ANY entryTags IN %@", selectedTags];

... this will return any Entry with at least one entryTag that is in the selectedTags set.

I want something along the lines of:

[NSPredicate predicateWithFormat:@"ALL entryTags IN %@", selectedTags];

... notice the only change is the "ANY" to "ALL". This illustrates what I want, but does not work.

To formulate the outcome I expect:

I'm looking for a solution that will return only Entries who's entryTags are all in the selectedTags list (but at the same time, if possible, not necessarily the other way around).

To further illustrate:

(tag)Mom
(tag)Dad
(tag)Gifts

(entry)she is a she.....(tag)mom
(entry)he is a he........(tag)dad
(entry)gifts for mom...(tags:)mom, gifts
(entry)gifts for dad.....(tags:)dad, gifts

If selectedTags contains "mom" and "gifts", then the entry "gifts for dad" will show up, since it has the tag "gifts". I'd rather have it not show :)

Answer

Stian Høiland picture Stian Høiland · Mar 31, 2012

This is the definite answer so far:

[NSPredicate predicateWithFormat:@"SUBQUERY(entryTags, $tag, $tag IN %@).@count = %d", selectedTags, [selectedTags count]];

B-E-A-U-T-I-F-U-L.

Thanks to Dave DeLong.