UITableViewDiffabledatasource NSFetchedResultController: how to update in case of change

Viewed 242

I'm setting up a tableView with the new UITableViewDiffabledatasource and an NSFetchedResultController.

Insertion and deletion are correctly being handle out of the box. But when an item is updated (as in one of it's property is updated) and the cell displaying that item should be updated, it does not get updated.

How can I got about making sure the UITableViewDiffabledatasource sees that change and fires a refresh of the cell?

Adding the code I'm using:

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.dataSource = dataSource
}

func makeDataSource() -> UITableViewDiffableDataSource<String, NSManagedObjectID> {
    let reuseIdentifier = String(describing: RegisterTableCell.self)

    let dataSource =  UITableViewDiffableDataSource<String, NSManagedObjectID>(
        tableView: tableView,
        cellProvider: {  tableView, indexPath, objectID in
            let cartItem = try! self.container.viewContext.existingObject(with: objectID) as! CartItem
            let cell = tableView.dequeueReusableCell(
                withIdentifier: reuseIdentifier,
                for: indexPath
            ) as! RegisterTableCell

            cell.count.text = String(format: "%@", cartItem.count ?? "0")
            cell.label.text = cartItem.name
            cell.price.text = self.priceFormatter.string(from: NSNumber(value: cartItem.totalPrice()))
            return cell
        }
    )
    dataSource.defaultRowAnimation = .left
    return dataSource
}


func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
    updateUI()
    let diffableSnapshot = snapshot as NSDiffableDataSourceSnapshot<String,NSManagedObjectID>
    dataSource.apply(diffableSnapshot, animatingDifferences: true, completion: nil)
}
0 Answers
Related