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

随声附和 提交于 2019-11-26 07:48:14

问题


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?


回答1:


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.




回答2:


Have you tried:

NSPredicate *predicate = [NSPredicate predicateWithFormate:@"items == %@", itemSet];

Alternatively, pull out a subset with a simpler predicate and filter them outside of the fetch request. i.e.

  1. Set a predicate for the number of items in the relationship to the be the same as the number of items in your comparison set.
  2. Fetch the results
  3. Filter these results to show only the ones where the sets contain the same items.


来源:https://stackoverflow.com/questions/13084930/how-to-create-a-core-data-predicate-to-test-that-a-relation-contains-all-given-o

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