swift UICollectionViewDiffableDataSource -当具有不同散列的相等项时崩溃

whlutmcx  于 2024-01-05  发布在  Swift
关注(0)|答案(1)|浏览(122)

我使用UICollectionViewDiffableDataSource来填充UICollectionView的数据。我的理解是,DiffableDataSource通过使用==来比较项目,然后如果项目相等,则比较hash的值以查看是否有变化。
但根据我得到的错误,情况并非如此。

  1. Diffable data source detected item identifiers that are equal but have different hash values. Two identifiers which compare as equal must return the same hash value. You must fix this in the Hashable (Swift) or hash property (Objective-C) implementation for the type of these identifiers

字符串
在我的例子中,我有一个与uniqueID进行比较的项目,hashValue由用户输入的值确定。如果它们不能不同,那么使用==和hashValue有什么意义呢?

iyfamqjs

iyfamqjs1#

解决方法:通过hashValue和uniqueID进行相等,以避免equal but have different hash values崩溃。

  1. static func == (lhs: Item, rhs: Item) -> Bool {
  2. lhs.hashValue == rhs.hashValue && lhs.id == rhs.id
  3. }

字符串
也许不是一个完美的解决方案。在我的例子中,我只需要==来移动动画,所以当只有一个项目改变并需要移动时,我通过通知发送改变的值,并在动画后替换项目:

  1. dataSource.apply(snapshot, animatingDifferences: true) { [weak self] in
  2. guard let self else { return }
  3. snapshot.insertItems([newItem], beforeItem: item)
  4. snapshot.deleteItems([item])
  5. snapshot.reconfigureItems([newItem])
  6. dataSource.apply(snapshot, animatingDifferences: false)
  7. }


不能同意更多关于'如果它们不能不同,使用==和hashValue有什么意义':)

展开查看全部

相关问题