简体   繁体   中英

Correct way to update model variable inside UICollectionViewDiffableDataSource in iOS

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.

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

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