Search code examples
iosswiftuitableviewnsfetchedresultscontroller

Fetch multiple entities with relation between them with one NSFetchedResultController


I have base class Worker and subclasses Employee, Bookkeeper and Director and entities for them in xcdatamodeld. Now I want to use NSFetchedResultController to fetch them into tableView so that each entity in each section. I dont know how to do that with single frc. Any help.

enter image description here


Solution

  • An NSFetchedResultsController can only work with one entity at a time. that will be ok for you since your classes inherit from the worker entity but you are not able to supply a keypath that can determine the subtype which would be used for the sections. The solution I would suggest would be to add a type attribute to the Worker entity which could be a simple as an Int and then in each subclass set the value during the initialisation to be a different value for each type. Eg.

    directorInstance.type = 1
    

    ...

    employeeInstatnce.type = 2
    

    Then define your NSFetchedResultsController:

    var fetchRequest = NSFetchRequest(entityName: "Worker")
    fetchRequest.predicate = NSPredicate(format: "lastName contains[cd] %@", nameSearchTerm)
    var frc = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: "type", cacheName: nil)