Search code examples
ioscore-datansfetchedresultscontroller

How to fetch entities from CoreData in order of their relationship order to another entity


So I have a CoreData entity "A" that has a to-many relationship with entity "B". "A" has many "B"s. This relationship is Ordered!

I know that I can get the NSOrderedSet directly from entity "A"s relationship. BUT I have a UITableView and I'd like to use an NSFetchedResultsController with it because I believe that is better practice.

How do I get the NSFetchedResultsController to sort the entities based on their order in the relationship?


Solution

  • If A is Manager and B is Employee, and the relationships are Manager.underlings (to-many ordered), and Employee.boss (to one), then you would use

    NSSortDescriptor(key: "boss", ascending: true)]
    

    And that will sort according to the Employee's ordered relationship with the manager.