首页 > 解决方案 > UITableViewDiffabledatasource NSFetchedResultController:发生变化时如何更新

问题描述

我正在使用新的 UITableViewDiffabledatasource 和 NSFetchedResultController 设置 tableView。

开箱即用地正确处理插入和删除。但是当一个项目被更新(如它的一个属性被更新)并且显示该项目的单元格应该被更新时,它不会被更新。

我怎样才能确保 UITableViewDiffabledatasource 看到该更改并触发单元格的刷新?

添加我正在使用的代码:

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)
}

标签: uitableviewnsfetchedresultscontrollernsmanagedobject

解决方案


推荐阅读