CoreData: Sort and Section on Relationships
I have two questions about using Core Data. Taking the typical case of Employee and Department as an example. The Employee entity has a relationship field 开发者_如何学JAVA"deparment" as to-one to Department, and the Department entity has a relationship "employee" as to-many to Employee entity.
I would like to display all the employees in a TableView in sections of department's names. I think that the NSFetchedResultsController should use Employee as entity. I am not sure how to use Department's name as a sort criteria, since it is in an employee's relationship field department's name. Can you use "DepartmentName" as a sort and add this to Employee entity class as a method which will return department's name for a given employee?
The second question is the section name. I would like to use department names as sections. Can I use the above method as sectionKeyPath's value for the NSFethedResultsController?
Not sure if I am on the right track.
You can set the sort key to be department.name for the sectionKey as well as the sort. You can even sort first by department.name and then by the employee's name.
update
The string "department.name" can be used both as the sort key in the NSSortDescriptor
and as the section name in the construction of the NSFetchedResultsController
.
This is a part of Key Value Coding and highly recommend that you read up on it as there is a lot of power and flexibility lurking in there.
精彩评论