开发者

UITableView and Core Data to-many relationships

I've got a problem with UITableViews and many-to-many relationships.

I have two classes, A and B, that both extend NSManagedObject and live in Core Data. Each has a to-many relationship to the other:

A<<-->>B

I would like to use objects of class A as the sections of a UITableView, and it's set of B objects as "data rows" in the TableView. Is this possible, and what would be the best approach to achieve this? Preferably I would like to use a NSFetchedResultsController to manage the data presented by the UITableView开发者_JS百科, but so far I have not been able to come up with a predicate and section name key path that works.


You can't use a fetched results controller to do this.

If the A objects are the section names and each B objects has many A relationships then each B can show up in the table multiple times in different sections. Core Data is really set up around the idea of unique objects and all the boilerplate code for tableviews assumes that each row represents a single unique object. In this circumstance, even counting the number of rows would be difficult and the sectionNameKeyPath would be impossible to set because it could have multiple values at any one time.

You need to configure all this by hand. You'll have to fetch the A objects and then set the section titles, then you will have to get each A.bObjs and count and sort them for the rows in each section completely individually. Deleting an exist B object might prove difficult because it could trigger the removal of multiple rows at the same time.

I would urge you to rethink your design. Sections and section titles are not supposed to represent managed objects but rather a grouping of the managed objects represented by the rows based on one of the row object's attributes. What you really want here is a master-detail view hierarchy. The top tableview will show all the A objects. When a row is selected, it loads the second tableview that shows all the B objects related to the selected A object.


I would use NSFetchedResultsController to watch over the A objects. Use your fetched results to populate the section titles. Then when you are looking to populate your "data rows", you can find your current A object (by using [[fetchedResultsController fetchedResults] objectAtIndex:indexPath.section] or something similar) and extract the B objects from it with A.BOjbects, which returns the NSSet of all B objects associated with the A object. After doing that, you can filter or sort the list as you please before placing them in the rows

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜