Create NSFetchedResultsController managing entities with many to many relationship
I have an entity called Project
and another entity called Employee
. Employees work on multiple projects.
Project
entity has project name
.
Employee
entity has First name
, last name
, departmentid number
.
I want the data to show up in section header table like this
Project 1
Dept1 -firstname1, lastname1 -firstname2,lastname2 dept 2 firstname3, lastname3 firstname4,lastname4 Project 2 Dept1 -firstname1,lastname1
How can I do this? I don't have to display department names, but it has to be sorted that way.开发者_JS百科
I am using Core Data & UITableView
. I need to construct NSFetchResultsController
for this.
I think the root of your question comes from the fact that a to-many relationship results in an NSSet when you access it from the from object of the relationship (ie: Project->Employees - results in an NSSet of employees). NSSets are, of course, unordered.
And the answer is this:
You'll need to sort your employee NSSets by hand. I suggest you convert the NSSet to an NSMutableArray, and then use -sortUsingBlock: or something along those lines to do it. To keep yourself from having to re-sort it every time you need it, store it as a member variable of your Project class. In doing so, it should be pretty easy to create it lazily, and only re-sort it when the dataset changes, which will be better for performance.
You MIGHT be able to do something with a subquery in Core Data... but I think you might find that'll hit the disk more often than you might like. (Just a guess there) The technique I've suggested above is a bit less magical, a bit more brute force, but it'll work, and you'll know exactly how it behaves forever.
Use fetchedResultsController to get your 'Project' entities and you will be able to access and display the Employee
NSSet in your tableview datasource methods via their relationships.
精彩评论