1

I have a UITableViewController with NSFetchedResultsController connected to it.

It's implemented pretty closely to Apple guide here:

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/nsfetchedresultscontroller.html#//apple_ref/doc/uid/TP40001075-CH8-SW1

func initializeFetchedResultsController() {
    let request = NSFetchRequest(entityName: "Person")
    let departmentSort = NSSortDescriptor(key: "department.name", ascending: true)
    let lastNameSort = NSSortDescriptor(key: "lastName", ascending: true)
    request.sortDescriptors = [departmentSort, lastNameSort]
    let moc = dataController.managedObjectContext
    fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: moc, sectionNameKeyPath: "department.name", cacheName: nil)
    fetchedResultsController.delegate = self
    do {
        try fetchedResultsController.performFetch()
    } catch {
        fatalError("Failed to initialize FetchedResultsController: \(error)")
    }
}

I have custom cells for section headers. In the section header I'm showing department name and number of employees within a department (which is a stored property).

The problem I have is that when number of employees is updated, didChangeSection is never called.

Should I monitor didChangeObject and reload the section or is there a better way?

undsoft
  • 789
  • 2
  • 12
  • 21
  • Have you tried to use a transient property for `sectionNameKeyPath`? – luish Jul 20 '16 at 12:04
  • No, I haven't. So, you're saying it would be a good practice to glue several properties together in sectionNameKeyPath? – undsoft Jul 20 '16 at 12:24
  • it's quite a common practice as you can see in other threads here: http://stackoverflow.com/a/30947319/1431949 – luish Jul 20 '16 at 12:40
  • Okay, I'm not sure it works. I've added a getter that returns compound property that I need in sections. Then I've added it to sectionNameKeyPath. However when I create Employees, I end up with new sections for every added Employee. As soon as I restart the tableview, sections are sorted correctly. – undsoft Jul 20 '16 at 13:43
  • So far I'm reloading the whole section when any row is updated within the section. – undsoft Jul 20 '16 at 14:37
  • I'm not totally sure about it, but can't you detect which row was modified within that section? Maybe with some verification inside `controller(_:didChange:at:for:newIndexPath:)`. – luish Jul 20 '16 at 14:46
  • 1
    I would use the FRC's `didChangeObject` delegate method, but use `headerViewForSection` to get the relevant header (which might be nil if it's off screen) then update the relevant label/other UI with the new employee count. Avoids the need to reload the entire section just for one label update. – pbasdf Jul 20 '16 at 20:10

0 Answers0