简体   繁体   中英

DiffableDataSource re-create all section after update array

I created a struct for UICollectionViewDiffableDataSource

struct Section: Hashable {
   let name: String
   let items: [Int]
}

And created snapshot with this structure

func updateData(for data: [Section]) {
  var snapshot = NSDiffableDataSourceSnapshot<Section, Int>()
  snapshot.appendSections(data)
  for section in data {
    snapshot.appendItems(section.items, toSection: section.name)
  }
  dataSource.apply(snapshot, animatingDifferences: false)
}

And here how I setup initial Data

updateData(for: [Section(name: "T", items: [1, 2]), Section(name: "J", items: [3, 4, 5]))

And if I trying add more item with this method:

updateData(for: [Section(name: "T", items: [1, 2]), Section(name: "J", items: [3, 4, 5 ,6])])

All Section "J" re-created Why this happened?

Here the example where when cell after 1 second of loading - change color to green And here we can see, what second section - re-created

https://media.giphy.com/media/G3FEoQTarVN0NiYHTT/giphy.gif

Your Section identifier is the hash of the section object. It is the hash of all its properties including the array of items. If any of these properties change the hash changes causing the section to reload.

For the diffable data source it looks like a brand new section. So it destroys the old one and adds the new one. What you should use instead is just the id of the section - in your case the name. In this case it will only update the new individual items.

This idea applies to items too. In your case they are simple Int - so that's not an issue.

But if you had a struct conforming to hashable - the entire cell would be destroyed and reloaded when one of the structs properties change. Instead you want to pass just the id of the item to the data source and update the views in your cell yourself by observing the values in your data. This way cells are only destroyed when an entirely new model is added or removed from the data source.

This is described in the docs And has been explained in WWDC 21

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM