Search code examples
core-datanspredicatenssetnsfetchedresultscontroller

In Core Data, how to get all object of NSSet?


I currently have the following Core Data Model:

Category

@interface Category : NSManagedObject
@property (nonatomic, retain) NSSet *subcategory;

Subcategory

@interface SubCategory : NSManagedObject
@property (nonatomic, retain) Category *category;
@property (nonatomic, retain) NSSet *items;

Items

@interface Item : NSManagedObject
@property (nonatomic, retain) SubCategory *subCategory;

I want to get all items in a category, however when I write:

NSLog(@"Items in Category:%@", self.category.subcategory.items)

I get nothing.

What would be the way to fetch the information? Since I am receiving the class with a property I added in the ViewController:

@property (strong, nonatomic) Category *category;

Solution

  • One possible solution is to use the Key-Value Coding Collection Operator @distinctUnionOfSets:

    NSSet *allItems = [self.category valueForKeyPath:@"subcategory.@distinctUnionOfSets.items"];
    

    (Note that a better name for the to-many relationship "subcategory" would be "subcategories".)

    Alternatively, you can execute a fetch request on the "Item" entity with a predicate using the inverse relationships:

    [NSPredicate predicateWithFormat:@"subCategory.category == %@", self.category];
    

    The advantage of this method is that the intermediate "SubCategory" objects are not loaded into memory.