5
votes

I have a request like this :

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY attributes.attribute.attributeId IN %@", attributeIds];

That will return a list of objects, that have one ore more of the attributes I set. I want to get a list of objects that have all the attributes I pass, so I tried :

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ALL attributes.attribute.attributeId IN %@", attributeIds];

But I got an exception :

'NSInvalidArgumentException', reason: 'Unsupported predicate (null)'

Anyway, I'm not even sure that this is the right request. Say that I have at list of attributes : [red, green, blue], How can I get all objects that have at least those attributes ?

* Object_1 (red, green, blue)
* Object_2 (red, green, blue, yellow, brown)
* Object_3 (red, green blue, black, brown)

but not Object_4 (red, green, yellow) because it doesn't have the blue attribute (note that I get all 4 objects with my ANY fetch request, as expected)

edit, related question : what if I want a full match ? So for [red, green, blue] I will only get Object_1 ?


edit 2 : I managed to answer both questions, but I have a new one

1

1 Answers

6
votes

Fetch all Objects that have at least all attributes in list

NSPredicate *objectsThatContainsAtLeastAllAttributesInList =
    [NSPredicate predicateWithFormat:
        @"SUBQUERY(attributes, $s, $s.attribute.attributeId IN %@).@count == %d", attributeIds, [attributeIds count]];    

Fetch all Objects that have only the attributes in list

NSPredicate *objectsWhoseAttributesAreInList =
    [NSPredicate predicateWithFormat:
        @"attributes.@count == %d AND SUBQUERY(attributes, $s, $s.attributes.id IN %@).@count == %d", [attributeIds count], attributeIds, [attributeIds count]];