Created
December 14, 2019 15:35
-
-
Save pixlwave/c4216b62ea0e89ad6d69d1ddad85bf9a to your computer and use it in GitHub Desktop.
NSDiffableDataSourceSnapshot reloadItems
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Crashes when reloading an item if Thing is a class and not a struct.