开发者

CoreData model with nested object relationships as a datasource?

开发者 https://www.devze.com 2023-03-01 02:12 出处:网络
I have a very simple data model that consists of 2 objects — a Section and an Item. Each Section has a to-many child relationship to other Section objects as well as a to-one parent relationship with

I have a very simple data model that consists of 2 objects — a Section and an Item. Each Section has a to-many child relationship to other Section objects as well as a to-one parent relationship with another Section object. Every section has a to-many relationship to Item objects.

CoreData model with nested object relationships as a datasource?

Structure aside, some Section objects have no Item objects, and others (at the bottom of the hierarchy) have no Section child objects.

I want to create a tableview that will use Section objects to create the section headers, and then display the Item objects as tableViewCells that are a part开发者_StackOverflow社区 of that Section. I also want table headers to appear if the Section has no Items, because seeing the hierarchy is important.

Given a random Section object, how would I go about fetching and displaying this data? Do I need to create a nested loop that flattens the data in an array, or is there some awesome way to leverage predicates and NSFetchedResultsController?


I would build your NSFetchedResultsController with a sort descriptor that sorts the items by the section's ID.

Something like:

NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"section.ID" ascending:YES];

This will give your NSFetchedResultsController all the correct items grouped by section. Then you just need to flesh out your table view datasource and delegate accordingly.


  1. Set your fetch entity to Item
  2. Provide the fetch two sort descriptors. The first should sort on section.ID and the second should sort on id. That will return an array of Item objects sorted first by section and then by their own id attribute.
  3. When initializing the fetched result controller, set the sectionNameKeyPath parameter to section.ID. That will cause the section names to display as the Section.ID values.

That should give you a table like this:

Section.ID
    Item.ID
    Item.ID
    Item.ID
Section.ID
    Item.ID
.... and so on.
0

精彩评论

暂无评论...
验证码 换一张
取 消