What is the best practice to ensure changes to the sectionKeyPathName
values (which are from a related entity) are propagated to the UITableView's section headers (includes redrawing the section headers with the new value and changing the section ordering if needed)?
I am under the assumption that the NSFetchedResultsController delegate's current capabilities cannot meet my needs because
- The
NSFetchedResultsController
is observing the one entity (Recipe in my case for the table rows) and not the entity of thesectionKeyPathName
(Category's name property for me.) - The
NSFetchedResultsController
delegate'scontroller(_:didChange:atSectionIndex:for)
never returns move or update for its type parameter
Background
I have two entities, Category and Recipe, where a Category can have multiple Recipes and a Recipe will belong to only 1 Category (aka 1:M relationship.)
I have a tableview of Recipes, with a section for each Category. The section header is the Category's name. I have used a fetchedResultsController to populate the table view. Everything works as expected (i.e., as Recipes are updated, added, deleted or have their Category changed, the table view reflects those changes) with ONE EXCEPTION. I cannot get the section headers to change when a Category name changes. I want not only the headers to reflect a changed name but to re-sort as needed.
Code Snippets
I'll share as needed. As I said everything else works and there is a lot of code.
FWIW - My sectionKeyPathName
value is the same as the first value of the sortDescriptor array.
Failed Attempt
I assume I need to observe the Category's name
property for changes. Worst case, my sections would need re-ordering. Hence, if the name
changed, I would just performFetch()
again and then reloadData()
on the table. I tried this technique.
- Observe
NSManagedObjectContextWillSave
to determine if a Category (that was currently a section in my table view) had itsname
property change. - If
name
property changed, then when I observedNSManagedObjectContextDidSave
, I would perform the fetch again and reloadData(). This seemed to solve the problem but then crashed when I tested moving a Recipe to a different Category. (The moving test worked prior to this change.) (The crash isAn exception was caught from the delegate of NSFetchedResultsController during a call to -controllerDidChangeContent:. Invalid update: invalid number of sections.
)