1

Ok, I've got a preliminary working version of a collectionview with a diffable datasource. All is working and I just implemented adding and changing items, and deleting items still to be done. There is little information out there as of current on adding, changing and deleting items with a diffable datasource. I wonder if all the array stuff I do is the way to go. I feel I should do more with the snapshot. Should all logic from the save method be in the update method? Any help appreciated and/or any resources on the matter

ProjectsViewController: UIViewController {
(...)
    //DataSource methods (snapshot)
    func updateData(on projects: [Project]) {
        var snapshot = NSDiffableDataSourceSnapshot<Section, Project>()
        snapshot.appendSections([Section.normal])
        snapshot.appendItems(projects)

        //apply() is safe to call from a background queue!
        self.dataSource.apply(snapshot, animatingDifferences: true)
    }

(...)
}

//MARK: - ProjectHandler (delegation method)
extension ProjectsViewController: ProjectHandler {
    func save(_ project: Project, withImage image: UIImage?) {
        //Make sure LastEdited Date gets updated
        var projectToBeSaved = project
        projectToBeSaved.lastEdited = Date()

        //Current state
        var projects = dataSource.snapshot().itemIdentifiers

        //Replace the changed project
        if projects.contains(projectToBeSaved) {
            let index = projects.firstIndex(of: projectToBeSaved)
            projects.remove(at: index!)
            projects.append(projectToBeSaved)
        //Add the new projects
        } else {
            projects.append(projectToBeSaved)
        }

        //sort on lastly edited
        projects.sort { $0.lastEdited > $1.lastEdited }

        //TODO: - Write to json

        //update the snapshot
        updateData(on: projects)
        collectionView.reloadData()
    }
}

DeveloperSammy
  • 167
  • 1
  • 11
  • Were you able to figure out the best way to change data? I'm currently having that issue right now – fphelp Jul 12 '20 at 18:14
  • No, I find it quite hard to find good information on diffable data source. Thinking about reverting to a classic datasource ... – DeveloperSammy Jul 14 '20 at 12:49

1 Answers1

0

FYI- I was having an issue updating data with diffable data source. All my cells were disappearing when I switched my segmented control, sometimes.

I just got the latest Xcode and this particular issue is solved Version 14.1 (14B47b)

devjme
  • 684
  • 6
  • 12