Correct way to update model variable inside UICollectionViewDiffableDataSource in iOS

175 Views Asked by At

I'm developing an application with UICollectionViewDiffableDataSource. Everything works like a charm, in fact I've got my collectionView updated automatically when I add a new model. However I'm unable to see updated cell when I update one of my present elements.

Here's an example:

I've got this model

final class Contact: Hashable {
    var id: UUID
    var name: String
    
    init(id: UUID = UUID(), name: String) {
        self.id = id
        self.name = name
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
        hasher.combine(name)
    }
    static func == (lhs: Contact, rhs: Contact) -> Bool {
        
        return lhs.id == rhs.id
    }
    
}

which populates my UICollectionView. If I try to update for example its name on didSelectItem, and then call my function which analyze differences with NSDiffableDataSourceSnapshot, it doesn't update my UICollectionView. If I add another Contact on didSelect (just for test), my UICollectionView got updated perfectly as I want.

1

There are 1 best solutions below

0
On

I've just solved on my own. I tried to change class declaration to struct instead of final class. I don't really know why, but it seems that in array of items declared as Class, snapshot check if reference is the same, but not its content. So it doesn't update view when I update any variable, even if I added them to either hash required function and equatable required function