Skip to content

Instantly share code, notes, and snippets.

@pixlwave
Created December 14, 2019 15:35
Show Gist options
  • Save pixlwave/c4216b62ea0e89ad6d69d1ddad85bf9a to your computer and use it in GitHub Desktop.
Save pixlwave/c4216b62ea0e89ad6d69d1ddad85bf9a to your computer and use it in GitHub Desktop.
NSDiffableDataSourceSnapshot reloadItems
import UIKit
class ViewController: UITableViewController {
var things = [Thing]()
var dataSource: UITableViewDiffableDataSource<Int, Thing>!
override func viewDidLoad() {
super.viewDidLoad()
things = [Thing(), Thing(), Thing(), Thing(), Thing()]
dataSource = UITableViewDiffableDataSource<Int, Thing>(tableView: tableView, cellProvider: { tableView, indexPath, thing -> UITableViewCell? in
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") ?? UITableViewCell()
cell.textLabel?.text = "\(thing.id)"
return cell
})
tableView.dataSource = dataSource
var snapshot = NSDiffableDataSourceSnapshot<Int, Thing>()
snapshot.appendSections([0])
snapshot.appendItems(things)
dataSource.apply(snapshot)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if let data = try? JSONEncoder().encode(things) {
let newThings = try! JSONDecoder().decode([Thing].self, from: data)
print("Things: \(things)")
print("New Things: \(newThings)")
things = newThings
}
var snapshot = dataSource.snapshot()
snapshot.reloadItems([things[2]])
dataSource.apply(snapshot)
}
class Thing: Codable, Hashable, CustomStringConvertible {
static func == (lhs: Thing, rhs: Thing) -> Bool {
lhs.id == rhs.id
}
let id: UUID
init() {
id = UUID()
}
var description: String {
return "Thing: \(id)"
}
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
}
}
@pixlwave
Copy link
Author

Crashes when reloading an item if Thing is a class and not a struct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment