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.

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.
- Set your fetch entity to
Item - Provide the fetch two sort descriptors. The first should sort on
section.IDand the second should sort onid. That will return an array ofItemobjects sorted first by section and then by their ownidattribute. - When initializing the fetched result controller, set the
sectionNameKeyPathparameter tosection.ID. That will cause the section names to display as theSection.IDvalues.
That should give you a table like this:
Section.ID
Item.ID
Item.ID
Item.ID
Section.ID
Item.ID
.... and so on.
加载中,请稍侯......
精彩评论