From b6553c0b59ee2fe2d464d8a33c755bb544f0c76c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sat, 12 Oct 2019 14:49:18 +0200 Subject: [PATCH] Demo app: replace FetchedRecordsController with ValueObservation --- .../GRDBDemoiOS.xcodeproj/project.pbxproj | 34 ++++++- .../xcschemes/GRDBDemoiOS.xcscheme | 8 +- DemoApps/GRDBDemoiOS/GRDBDemoiOS/Player.swift | 3 + .../GRDBDemoiOS/PlayersViewController.swift | 99 ++++++++++--------- DemoApps/GRDBDemoiOS/README.md | 4 +- 5 files changed, 89 insertions(+), 59 deletions(-) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index f22440fa0..887804850 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -36,6 +36,20 @@ remoteGlobalIDString = 56439B501F4CA1DC0066043F; remoteInfo = GRDBOSXPerformanceComparisonTests; }; + 56606CDC2351F68400185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = AAA4DCFE230F1E0600C74B15; + remoteInfo = GRDBtvOS; + }; + 56606CDE2351F68400185962 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; + proxyType = 2; + remoteGlobalIDString = AAA4DDD4230F262000C74B15; + remoteInfo = GRDBtvOSTests; + }; 568E5FCD1E926430002582E0 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */; @@ -288,6 +302,8 @@ 56B0364D1E8D9F79003B6DA4 /* GRDB.framework */, 56B0364F1E8D9F79003B6DA4 /* GRDBiOSTests.xctest */, 56B0365B1E8D9F79003B6DA4 /* GRDB.framework */, + 56606CDD2351F68400185962 /* GRDB.framework */, + 56606CDF2351F68400185962 /* GRDBtvOSTests.xctest */, ); name = Products; sourceTree = ""; @@ -417,6 +433,20 @@ remoteRef = 563BD2F01F8364C1006A5390 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; + 56606CDD2351F68400185962 /* GRDB.framework */ = { + isa = PBXReferenceProxy; + fileType = wrapper.framework; + path = GRDB.framework; + remoteRef = 56606CDC2351F68400185962 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; + 56606CDF2351F68400185962 /* GRDBtvOSTests.xctest */ = { + isa = PBXReferenceProxy; + fileType = wrapper.cfbundle; + path = GRDBtvOSTests.xctest; + remoteRef = 56606CDE2351F68400185962 /* PBXContainerItemProxy */; + sourceTree = BUILT_PRODUCTS_DIR; + }; 56B0363B1E8D9F79003B6DA4 /* GRDB.framework */ = { isa = PBXReferenceProxy; fileType = wrapper.framework; @@ -708,7 +738,7 @@ SDKROOT = iphoneos; SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; }; name = Debug; }; @@ -759,7 +789,7 @@ MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; - SWIFT_VERSION = 4.2; + SWIFT_VERSION = 5.0; VALIDATE_PRODUCT = YES; }; name = Release; diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme index 78cd878d4..cfd6faf50 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoiOS.xcscheme @@ -27,8 +27,6 @@ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"> - - - - + + - - ! + private var players: [Player] = [] + private var playersObserver: TransactionObserver? private var playerCountObserver: TransactionObserver? private var playerOrdering: PlayerOrdering = .byScore { didSet { - try! playersController.setRequest(playersRequest) configureOrderingBarButtonItem() + configureTableView() } } private var playersRequest: QueryInterfaceRequest { @@ -79,7 +80,8 @@ class PlayersViewController: UITableViewController { onError: { error in fatalError("Unexpected error: \(error)") }, - onChange: { [unowned self] count in + onChange: { [weak self] count in + guard let self = self else { return } switch count { case 0: self.navigationItem.title = "No Player" case 1: self.navigationItem.title = "1 Player" @@ -89,46 +91,49 @@ class PlayersViewController: UITableViewController { } private func configureTableView() { - // Track changes in the database players - playersController = try! FetchedRecordsController(dbQueue, request: playersRequest) - - // Animate changes in the table view - playersController.trackChanges( - willChange: { [unowned self] _ in - self.tableView.beginUpdates() - }, - onChange: { [unowned self] (controller, record, change) in - switch change { - case .insertion(let indexPath): - self.tableView.insertRows(at: [indexPath], with: .fade) - - case .deletion(let indexPath): - self.tableView.deleteRows(at: [indexPath], with: .fade) - - case .update(let indexPath, _): - if let cell = self.tableView.cellForRow(at: indexPath) { - self.configure(cell, at: indexPath) + // Track changes in the list of players + let request = self.playersRequest + let observation = ValueObservation.tracking { db in + try request.fetchAll(db) + } + playersObserver = observation.start( + in: dbQueue, + onError: { error in + fatalError("Unexpected error: \(error)") + }, + onChange: { [weak self] players in + guard let self = self else { return } + + // Compute difference between current and new list of players + let difference = players + .difference(from: self.players) + .inferringMoves() + + // Apply those changes to the table view + self.tableView.performBatchUpdates({ + self.players = players + for change in difference { + switch change { + case let .remove(offset, _, associatedWith): + if let associatedWith = associatedWith { + self.tableView.moveRow( + at: IndexPath(row: offset, section: 0), + to: IndexPath(row: associatedWith, section: 0)) + } else { + self.tableView.deleteRows( + at: [IndexPath(row: offset, section: 0)], + with: .fade) + } + case let .insert(offset, _, associatedWith): + if associatedWith == nil { + self.tableView.insertRows( + at: [IndexPath(row: offset, section: 0)], + with: .fade) + } + } } - - case .move(let indexPath, let newIndexPath, _): - // Actually move cells around for more demo effect :-) - let cell = self.tableView.cellForRow(at: indexPath) - self.tableView.moveRow(at: indexPath, to: newIndexPath) - if let cell = cell { - self.configure(cell, at: newIndexPath) - } - - // A quieter animation: - // self.tableView.deleteRows(at: [indexPath], with: .fade) - // self.tableView.insertRows(at: [newIndexPath], with: .fade) - } - }, - didChange: { [unowned self] _ in - self.tableView.endUpdates() + }, completion: nil) }) - - // Initial fetch - try! playersController.performFetch() } } @@ -139,7 +144,7 @@ extension PlayersViewController { override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "Edit" { - let player = playersController.record(at: tableView.indexPathForSelectedRow!) + let player = players[tableView.indexPathForSelectedRow!.row] let controller = segue.destination as! PlayerEditionViewController controller.title = player.name controller.player = player @@ -168,12 +173,8 @@ extension PlayersViewController { // MARK: - UITableViewDataSource extension PlayersViewController { - override func numberOfSections(in tableView: UITableView) -> Int { - return playersController.sections.count - } - override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - return playersController.sections[section].numberOfRecords + return players.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { @@ -184,14 +185,14 @@ extension PlayersViewController { override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { // Delete the player - let player = playersController.record(at: indexPath) + let player = players[indexPath.row] try! dbQueue.write { db in _ = try player.delete(db) } } private func configure(_ cell: UITableViewCell, at indexPath: IndexPath) { - let player = playersController.record(at: indexPath) + let player = players[indexPath.row] if player.name.isEmpty { cell.textLabel?.text = "-" } else { diff --git a/DemoApps/GRDBDemoiOS/README.md b/DemoApps/GRDBDemoiOS/README.md index 9c0eb9562..a4fde46ce 100644 --- a/DemoApps/GRDBDemoiOS/README.md +++ b/DemoApps/GRDBDemoiOS/README.md @@ -7,7 +7,7 @@ Demo Application - how to setup a database in an iOS app - how to define a simple [Codable Record](../../README.md#codable-records) -- how to track database changes and animate a table view with [FetchedRecordsController](../../README.md#fetchedrecordscontroller). +- how to track database changes and animate a table view with [ValueObservation](../../README.md#valueobservation). **Files of interest:** @@ -25,7 +25,7 @@ Demo Application - [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift) - `PlayersViewController` displays a list of players. It keeps its title up-to-date with [ValueObservation](../../README.md#valueobservation), and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller). + `PlayersViewController` displays a list of players. It keeps its view up-to-date with [ValueObservation](../../README.md#valueobservation). - [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift)