Swift DiffableDataSource 进行插入和删除而不是重新加载

Ang*_*lus 8 swift diffabledatasource

我很难理解 DiffableDataSource 是如何工作的。我有这样的 ViewModel

struct ViewModel: Hashable {
  var id: Int
  var value: String

  func hash(into hasher: inout Hasher) {
     hasher.combine(id)
  }
}
Run Code Online (Sandbox Code Playgroud)

我有 tableView 由 cachedItems 填充,如上面的 ViewModele。当 API 响应到达时,我想添加一个新的,删除缺失的一个,刷新 tableView 中已经存在的项目的 viewModel.value 并最终订购它。除了一件事 - 重新加载物品外,一切正常。

我对 DiffableDataSource 的理解是它比较 item.hash() 以检测项目是否已经存在,如果存在,那么如果 cachedItem != apiItem,它应该重新加载。不幸的是,这不起作用,快照确实删除和插入而不是重新加载。

DiffableDataSource 应该这样做吗?

当然,我有一个解决方案 - 为了使它工作,我需要遍历 cachedItems,当新项目包含相同的 id 时,我更新 cachedItem,然后我在没有动画的情况下应用快照,然后我终于可以应用带有动画的删除/插入/订购动画。

但是这个解决方案似乎更像是一个黑客而不是一个有效的代码。有没有更清洁的方法来实现这一目标?

更新:

有代码显示问题。它应该在操场上工作。例如。items 和 newItems 包含 id == 0 的 viewModel。哈希值相同,因此 diffableDataSource 应该重新加载,因为副标题不同。但是有可见的删除/插入而不是重新加载


import UIKit
import PlaygroundSupport

class MyViewController : UIViewController {
    let tableView = UITableView()

    var  diffableDataSource: UITableViewDiffableDataSource<Section, ViewModel>?

    enum SelectesItems {
        case items
        case newItems
    }

    var selectedItems: SelectesItems = .items

    let items: [ViewModel] = [ViewModel(id: 0, title: "Title1", subtitle: "Subtitle2"),
    ViewModel(id: 1, title: "Title2", subtitle: "Subtitle2"),
    ViewModel(id: 2, title: "Title3", subtitle: "Subtitle3"),
    ViewModel(id: 3, title: "Title4", subtitle: "Subtitle4"),
    ViewModel(id: 4, title: "Title5", subtitle: "Subtitle5")]

    let newItems: [ViewModel] = [ViewModel(id: 0, title: "Title1", subtitle: "New Subtitle2"),
    ViewModel(id: 2, title: "New Title 2", subtitle: "Subtitle3"),
    ViewModel(id: 3, title: "Title4", subtitle: "Subtitle4"),
    ViewModel(id: 4, title: "Title5", subtitle: "Subtitle5"),
    ViewModel(id: 5, title: "Title6", subtitle: "Subtitle6")]

    override func loadView() {
        let view = UIView()
        view.backgroundColor = .white
        self.view = view

        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        tableView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "CellID")

        diffableDataSource = UITableViewDiffableDataSource<Section, ViewModel>(tableView: tableView, cellProvider: { (tableView, indexPath, viewModel) -> UITableViewCell? in
            let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "CellID")
            cell.textLabel?.text = viewModel.title
            cell.detailTextLabel?.text = viewModel.subtitle
            return cell
        })
        applySnapshot(models: items)

        let tgr = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        view.addGestureRecognizer(tgr)
    }

    @objc func handleTap() {
        switch selectedItems {
        case .items:
            applySnapshot(models: items)
            selectedItems = .newItems
        case .newItems:
           applySnapshot(models: newItems)
           selectedItems = .items
        }
    }

    func applySnapshot(models: [ViewModel]) {
        var snapshot = NSDiffableDataSourceSnapshot<Section, ViewModel>()
        snapshot.appendSections([.main])
        snapshot.appendItems(models, toSection: .main)
        diffableDataSource?.apply(snapshot, animatingDifferences: true)
    }
}

enum Section {
    case main
}

struct ViewModel: Hashable {
    let id: Int
    let title: String
    let subtitle: String

    func hash(into hasher: inout Hasher) {
       hasher.combine(id)
    }
}


// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
Run Code Online (Sandbox Code Playgroud)

mat*_*att 5

这是因为您错误地实现了 Hashable。

请记住,Hashable 也意味着 Equatable——两者之间有着不可侵犯的关系。规则是两个相等的对象必须具有相等的哈希值。但是在您的 ViewModel 中,“相等”涉及比较所有三个属性idtitle、 和subtitle- 即使hashValue不是,因为您实现了hash.

换句话说,如果您实施hash,则必须实施==以完全匹配它:

struct ViewModel: Hashable {
    let id: Int
    let title: String
    let subtitle: String

    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    static func ==(lhs: ViewModel, rhs: ViewModel) -> Bool {
        return lhs.id == rhs.id
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您进行更改,您会发现表格视图动画的行为符合您的预期。

如果您希望表视图了解基础数据实际上已更改的事实,那么您还必须调用reloadData

    diffableDataSource?.apply(snapshot, animatingDifferences: true) {
        self.tableView.reloadData()
    }
Run Code Online (Sandbox Code Playgroud)

(如果您有其他原因希望 ViewModel 的 Equatable 继续涉及所有三个属性,那么您需要两种类型,一种用于执行简单而简单的相等比较时使用,另一种用于涉及 Hashable 的上下文,例如 diffable 数据源,集合和字典键。)

  • *“如果你实现了哈希,你必须实现 == 来精确匹配它”* – 我不这么认为。如果 `==` 比较三个属性(id、title 和 subtitle),并且 `hash` 仅对其中之一(id)进行哈希处理,那么仍然满足“相等对象必须具有相同哈希值”的约定。 (4认同)