0

I have 2 tables which are linked between themselves with many-to-many relationship.

SQL equivalent doesn't exist because it requires the third table to split a many-to-many relationship to two one-to-many relationships.

For example, I have two core data entities: category with a property (an array of items) and item with a property (an array of categories).

I need to get all the categories except of "empty" categories (when there is no item of this category).

My current temporary solution looks like an incorrect one. I use NSFetchRequest to get all the categories. Then I delete from this array all the categories with an empty item array manually using for-each.

user2083364
  • 744
  • 1
  • 7
  • 20

2 Answers2

1

In order to get all categories except the empty ones you could just use a predicate like this:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Category"];    
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"items.@count > 0"];
NSArray *categories = [context executeFetchRequest:fetchRequest error:NULL];
Florian Kugler
  • 688
  • 6
  • 10
  • Have you tried it by yourselft? terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here' and it was a problem for me – user2083364 Sep 25 '13 at 06:43
  • Sorry, typo. It should be `items.@count` instead of `items.count` – Florian Kugler Sep 25 '13 at 18:17
0

My solution:

[NSPredicate predicateWithFormat:@"ANY items != nil"]
user2083364
  • 744
  • 1
  • 7
  • 20