Search code examples
ioscore-datauikitcombine

How can I bind an NSManagedObject to a table/collection view cell using Combine?


I have an NSFetchedResultsController and a dynamic table view. My table view cells have a text label. How should I bind objects from the fetched results controller to the cell?

In WWDC 2019 230, there’s a code snippet where a core data object is bound to a view...

if let tag = try? fetchRequest.execute().first {
  nameSubscription = tag.publisher(for: \.name).assign(to: \.text, on: tagLabel)
  colorSubscription = tag.publisher(for: \.color).map({ $0 as? UIColor}).assign(to: \.textColor, on: tagLabel)
}

Where should this happen in the context of a table view controller with a cell that has a label? Where should the subscriber (AnyCancellable) go? Will I need a collection of subscribers since there’s an indefinite number of cells?


Solution

  • The binding like this was shown in WWDC session for the detail view, I guess.

    Table view cells are being reused during scrolling.

    That's why you're not supposed to bind the particular data model's property change to the update of the label in the cell.

    Instead, you should observe the changes to the data model on the controller level and reload table view cells and / or sections whenever changes happen.