Reputation: 1361
In my data model I have two entities:
Category and Item.
Category
attr: name
rel: parent (Destination: Category, Inverse: subCategories)
rel: subCategories (Destination: Category, Inverse: parent, To-Many Relationship)
rel: items (Destination: Item, Inverse: category, To-Many Relationship)
Item
attr: title
rel: category (Destination: Category, Inverse: items, To-Many Relationship)
Got the following TVC's: Root, Category, and Item
Root displays all Category objects with no parent
Category displays all Category objects with a certain parent object
Item displays all Item objects with a certain category
Example data:
Top Cat 1 - Sub cat 1 - Item 1 - Item 2 - Item 3 - Item 4 - Sub cat 2 - Item 1 - Sub cat 3 - Item 1 - Sub cat 4 - Item 1 - Item 2 - Sub cat 5 Top Cat 2 - Sub cat 1 - Item 1 - Item 2 - Item 3 - Sub cat 2 - Item 1 - Sub cat 3 - Item 1
So how do I get the total number of items per "Top Cat" when in the Root TVC?
If I want to know the number of "Sub cat"s I can use the following keyPath: "subCategories.@count" but something like "subCategories.items.@count" does not work.
Hope you can help me.
Cheers -Me
Upvotes: 1
Views: 1739
Reputation: 3827
There are three ways get the count:
Fire a fetch request for the top category in question, and from that object get the count of entities in it's sub-categories relationship set. The downside of this approach is that it will cause CoreData
to fetch the relationship property from the store, fetching every object associated with that relationship. e.g.
NSManagedObject *topCat = [context performFetch:topCatFetchRequest];
NSInteger count = topCat.subCategories.count;
Use raw SQLite
API's to query the data store directly (note this is much faster).
NSManagedObjectContext
countForFetchRequest:
, which will return the number of objects matching a given fetch request.Upvotes: 5