10

I'm using the new NSDiffableDataSourceSnapshot and UITableViewDiffableDataSource with a UITableView. I'm having no problems building the table but I'm having problems updating a cell when the data shown in it changes. I haven't found any Apple documentation explaining how to do this. I've tried the following:

self.currentSnapshot.reloadItems([Item(identifier: identifier)])
self.dataSource.apply(self.currentSnapshot)

I get the following error in reloadItems:

Assertion failure in -[__UIDiffableDataSourceSnapshot _reloadViewUpdatesForDiffUpdate:dataSource:ignoreInvalidItems:]

I have checked that the identifier passed to the Item initializer already exists in the snapshot.

Here is my Item class:

class Item: Hashable, Equatable {

    let identifier: String
    var matchWrapper: MatchWrapper

    init(matchWrapper: MatchWrapper) {
        self.identifier = matchWrapper.identifier
        self.matchWrapper = matchWrapper
    }

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

    static func == (lhs: ScoresViewController.Item, rhs: ScoresViewController.Item) -> Bool {
        return lhs.identifier == rhs.identifier
    }
}

Any suggestions?

cosmoonot
  • 2,161
  • 3
  • 32
  • 38
user12882508
  • 101
  • 1
  • 3
  • 1
    I know this question is a bit old but I thought I'd chime in. I wouldn't recommend using classes for your Item Identifiers. That will get you into trouble because they are reference types. That might be the reason for your crash but it's hard to tell without seeing how/where you are modifying your data. Also, you want to make sure that you are hashing and comparing (==) all of the fields that you want to display in your cell. That's the only way the data source will know any fields have changed. If you have more questions let me know. – Rob C Feb 24 '20 at 08:25
  • @RobertCrabtree Do you mean in this case `matchWrapper` must be part of the hash and `==` operator? Wouldn't that cause the data source to identify the "updated" objects where only the content of matchWrapper has changed as a new item when the expected result is updating the existing item? – Chamitha Jul 13 '20 at 03:54

3 Answers3

9

I have had similar problems and after a lot of debugging and trying out different things I've come to the conclusion that I don't think you should be using reloadItems. reloadItems doesn't actually seem to do anything from my testing. The cell provider always provides the old data and if you have a hash function based on an identifier and an equatable function that checks for equality on things other than the identifier, you get an error.

There are two things that you can try

  1. if you really want to use reload items in the cellProvider instead of using the data provided by the closure, use your own data source as the source of truth to lay out the cells. (this sort of defeats the purpose of diffableDataSource in my opinion though). You end up missing out on some of the great functionality of DiffableDataSource

  2. instead of writing code like this:

var snapshot = tableView.snapshot()
let item = items[indexPath.row]
snapshot.reloadItems([item]) 

you can do this

let snapshot: NSDiffableDataSourceSnapshot<Section,Item> = .init() 
// assuming wherever you're storing your data is already updated 
snapshot.appendItems([items])
dataSource.apply(snapshot)  

This should refresh only the items in the snapshot that have changes. From my understanding, the current snapshot of the tableView is compared with the newly created snapshot and only items that are different should be updated. I could be wrong here, but this is what has worked for me.

Other suggestions I've seen:

  • write your hash function combining all the values that can change in the view ex.
func hash(into hasher: inout Hasher) {
  hasher.combine(id)
  hasher.combine(name)
  hasher.combine(title)
}

however if you go this route this means that reloadItems will throw an error reporting that this doesn't exist in the data source so you'll have to add this and delete the old data manually

SymbolixAU
  • 25,502
  • 4
  • 67
  • 139
Matthew S.
  • 239
  • 2
  • 7
4

This worked or me:

func handleNewItems(_ newItems: [SomeItem]) {
    var snapShot = dataSource.snapshot()
    let diff = newItems.difference(from: snapShot.itemIdentifiers)
    let currentIdentifiers = snapShot.itemIdentifiers
    guard let newIdentifiers = currentIdentifiers.applying(diff) else {
        return
    }
    snapShot.deleteItems(currentIdentifiers)
    snapShot.appendItems(newIdentifiers)
    dataSource.apply(snapShot, animatingDifferences: true)
}
Noam
  • 620
  • 7
  • 13
  • Noam’s answer worked for me. I was trying to use the ‘reloadItems…’ API in macOS using the tableView diffableDataSource, and it kept giving me an exception. The only solution for me was to remove the items from the snapshot, apply the snapshot, reinsert the items to the snapshot, and apply again. – Zatman Jul 24 '21 at 22:57
1
guard var currentItem = datasource.itemIdentifier(for: indexPath)
    else { return }
    
    let nextItemIndexPath = IndexPath(item: indexPath.item + 1, section: indexPath.section)
    guard let nextItem = datasource.itemIdentifier(for: nextItemIndexPath)
    else { return }
    
    var snap = datasource.snapshot()
    snap.deleteItems([currentItem])
    currentItem.title = "Change/Update whatever attribute you want then Insert"
    snap.insertItems([currentItem], beforeItem: nextItem)
    datasource.applySnapshotUsingReloadData(snap)

I found a way and Its working. with "itemIdentifier(for: indexPath)" find a current item and delete item from snapshot so you can upload/insert the modified item into snap. I use "nextItemIndexPath" only to finding position of that item in tableview and insert in the same place/cell.

For my instance I using this inside "didSelectRowAt" in tableview. Hope you can save hours of time Unlike me lol