Core Data unsupported predicate with ALL and IN

依然范特西╮ 提交于 2019-11-29 10:24:27

问题


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:


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]];


来源:https://stackoverflow.com/questions/11346546/core-data-unsupported-predicate-with-all-and-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!