diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift index 517ff1842..a47810a6d 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PlayersViewController.swift @@ -1,22 +1,23 @@ import UIKit import GRDB +/// PlayersViewController displays the list of players. class PlayersViewController: UITableViewController { - enum PlayerOrdering { + private enum PlayerOrdering { case byName case byScore } - var playersController: FetchedRecordsController! - - var playerOrdering: PlayerOrdering = .byScore { + @IBOutlet private weak var newPlayerButtonItem: UIBarButtonItem! + private var playersController: FetchedRecordsController! + private var playerCountObserver: TransactionObserver? + private var playerOrdering: PlayerOrdering = .byScore { didSet { try! playersController.setRequest(playersRequest) - configureNavigationItem() + configureOrderingBarButtonItem() } } - - var playersRequest: QueryInterfaceRequest { + private var playersRequest: QueryInterfaceRequest { switch playerOrdering { case .byName: return Player.orderedByName() @@ -25,57 +26,59 @@ class PlayersViewController: UITableViewController { } } - @IBOutlet weak var newPlayerButtonItem: UIBarButtonItem! - override func viewDidLoad() { super.viewDidLoad() - configureTableView() configureToolbar() - configureNavigationItem() + configureOrderingBarButtonItem() + configureTitle() + configureTableView() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.isToolbarHidden = false } -} - - -// MARK: - Navigation - -extension PlayersViewController { - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "Edit" { - let player = playersController.record(at: tableView.indexPathForSelectedRow!) - let controller = segue.destination as! PlayerEditionViewController - controller.title = player.name - controller.player = player - controller.presentation = .push - } - else if segue.identifier == "New" { - setEditing(false, animated: true) - let navigationController = segue.destination as! UINavigationController - let controller = navigationController.viewControllers.first as! PlayerEditionViewController - controller.title = "New Player" - controller.player = Player(id: nil, name: "", score: 0) - controller.presentation = .modal + private func configureToolbar() { + toolbarItems = [ + UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)), + UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)), + UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), + UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)), + ] + } + + private func configureOrderingBarButtonItem() { + navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem] + + switch playerOrdering { + case .byScore: + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Score ⬇︎", + style: .plain, + target: self, action: #selector(sortByName)) + case .byName: + navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "Name ⬆︎", + style: .plain, + target: self, action: #selector(sortByScore)) } } - @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation cancelled + private func configureTitle() { + // Track changes in the number of players + playerCountObserver = try! ValueObservation + .trackingCount(withUniquing: playersRequest) + .start(in: dbQueue) { [unowned self] count in + switch count { + case 0: self.navigationItem.title = "No Player" + case 1: self.navigationItem.title = "1 Player" + default: self.navigationItem.title = "\(count) Players" + } + } } - @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { - // Player creation committed - } -} - - -// MARK: - UITableViewDataSource - -extension PlayersViewController { private func configureTableView() { // Track changes in the database players playersController = try! FetchedRecordsController(dbQueue, request: playersRequest) @@ -118,7 +121,44 @@ extension PlayersViewController { // Initial fetch try! playersController.performFetch() } +} + + +// MARK: - Navigation + +extension PlayersViewController { + override func prepare(for segue: UIStoryboardSegue, sender: Any?) { + if segue.identifier == "Edit" { + let player = playersController.record(at: tableView.indexPathForSelectedRow!) + let controller = segue.destination as! PlayerEditionViewController + controller.title = player.name + controller.player = player + controller.presentation = .push + } + else if segue.identifier == "New" { + setEditing(false, animated: true) + let navigationController = segue.destination as! UINavigationController + let controller = navigationController.viewControllers.first as! PlayerEditionViewController + controller.title = "New Player" + controller.player = Player(id: nil, name: "", score: 0) + controller.presentation = .modal + } + } + + @IBAction func cancelPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation cancelled + } + + @IBAction func commitPlayerEdition(_ segue: UIStoryboardSegue) { + // Player creation committed + } +} + + +// MARK: - UITableViewDataSource + +extension PlayersViewController { override func numberOfSections(in tableView: UITableView) -> Int { return playersController.sections.count } @@ -156,33 +196,6 @@ extension PlayersViewController { // MARK: - Actions extension PlayersViewController { - private func configureNavigationItem() { - navigationItem.leftBarButtonItems = [editButtonItem, newPlayerButtonItem] - - switch playerOrdering { - case .byScore: - navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "Score ⬇︎", - style: .plain, - target: self, action: #selector(sortByName)) - case .byName: - navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "Name ⬆︎", - style: .plain, - target: self, action: #selector(sortByScore)) - } - } - - private func configureToolbar() { - toolbarItems = [ - UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(deletePlayers)), - UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), - UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(refresh)), - UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil), - UIBarButtonItem(title: "💣", style: .plain, target: self, action: #selector(stressTest)), - ] - } - @IBAction func sortByName() { setEditing(false, animated: true) playerOrdering = .byName diff --git a/DemoApps/GRDBDemoiOS/README.md b/DemoApps/GRDBDemoiOS/README.md index f8e18ffb4..9c0eb9562 100644 --- a/DemoApps/GRDBDemoiOS/README.md +++ b/DemoApps/GRDBDemoiOS/README.md @@ -25,7 +25,7 @@ Demo Application - [PlayersViewController.swift](GRDBDemoiOS/PlayersViewController.swift) - `PlayersViewController` displays a list of players, and animates its table view according to database changes with [FetchedRecordsController](../../README.md#fetchedrecordscontroller). + `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). - [PlayerEditionViewController.swift](GRDBDemoiOS/PlayerEditionViewController.swift) diff --git a/Documentation/Images/GRDBDemoScreenshot.png b/Documentation/Images/GRDBDemoScreenshot.png index 8ca1c391f..f8f3a7bac 100644 Binary files a/Documentation/Images/GRDBDemoScreenshot.png and b/Documentation/Images/GRDBDemoScreenshot.png differ diff --git a/README.md b/README.md index 9657eebb8..a792bd056 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,7 @@ GRDB ships with: Companion libraries that enhance and extend GRDB: -- [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): track database changes in a reactive way, with [RxSwift](https://github.com/ReactiveX/RxSwift). +- [RxGRDB]: track database changes in a reactive way, with [RxSwift](https://github.com/ReactiveX/RxSwift). - [GRDBObjc](https://github.com/groue/GRDBObjc): FMDB-compatible bindings to GRDB. @@ -357,7 +357,7 @@ The repository comes with a [demo application](DemoApps/GRDBDemoiOS) that shows - how to setup a database in an iOS app - how to define a simple [Codable Record](#codable-records) -- how to track database changes and animate a table view with [FetchedRecordsController](#fetchedrecordscontroller). +- how to track database changes with [ValueObservation] and [FetchedRecordsController].

@@ -2061,7 +2061,7 @@ Before jumping in the low-level wagon, here is the list of all SQLite APIs used - `sqlite3_busy_handler`, `sqlite3_busy_timeout`: see [Configuration.busyMode](http://groue.github.io/GRDB.swift/docs/3.4/Structs/Configuration.html) - `sqlite3_changes`, `sqlite3_total_changes`: see [Database.changesCount and Database.totalChangesCount](http://groue.github.io/GRDB.swift/docs/3.4/Classes/Database.html) - `sqlite3_close`, `sqlite3_close_v2`, `sqlite3_next_stmt`, `sqlite3_open_v2`: see [Database Connections](#database-connections) -- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [ValueObservation], [FetchedRecordsController](#fetchedrecordscontroller) +- `sqlite3_commit_hook`, `sqlite3_rollback_hook`, `sqlite3_update_hook`: see [TransactionObserver Protocol](#transactionobserver-protocol), [ValueObservation], [FetchedRecordsController] - `sqlite3_config`: see [Error Log](#error-log) - `sqlite3_create_collation_v2`: see [String Comparison](#string-comparison) - `sqlite3_db_release_memory`: see [Memory Management](#memory-management) @@ -5782,8 +5782,8 @@ GRDB puts this SQLite feature to some good use, and lets you observe the databas - [After Commit Hook](#after-commit-hook): The simplest way to handle successful transactions. - [TransactionObserver Protocol](#transactionobserver-protocol): Low-level database observation. - [ValueObservation]: Automated tracking of database changes. -- [FetchedRecordsController](#fetchedrecordscontroller): Automated tracking of database changes, with table view animations. -- [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB): Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). +- [FetchedRecordsController]: Automated tracking of database changes, with table view animations. +- [RxGRDB]: Automated tracking of database changes, with [RxSwift](https://github.com/ReactiveX/RxSwift). Database observation requires that a single [database queue](#database-queues) or [pool](#database-pools) is kept open for all the duration of the database usage. @@ -5971,7 +5971,7 @@ do { > :point_up: **Note**: the databaseDidChange(with:) and databaseWillCommit() callbacks must not touch the SQLite database. This limitation does not apply to databaseDidCommit and databaseDidRollback which can use their database argument. -[ValueObservation], [FetchedRecordsController](#fetchedrecordscontroller), and [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) are based on the TransactionObserver protocol. +[ValueObservation], [FetchedRecordsController], and [RxGRDB] are based on the TransactionObserver protocol. See also [TableChangeObserver.swift](https://gist.github.com/groue/2e21172719e634657dfd), which shows a transaction observer that notifies of modified database tables with NSNotificationCenter. @@ -6601,7 +6601,7 @@ Given a fetch request, and a type that adopts the [FetchableRecord] protocol, su See the [Demo Application](DemoApps/GRDBDemoiOS) for an sample app that uses FetchedRecordsController. -When you don't need to animate a table or a collection view, use [ValueObservation] or [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) instead. +When you don't need to animate a table or a collection view, use [ValueObservation] or [RxGRDB] instead. - [Creating the Fetched Records Controller](#creating-the-fetched-records-controller) - [Responding to Changes](#responding-to-changes) @@ -7746,8 +7746,8 @@ These protocols provide a unified API that let you write generic code that targe - [Migrations](#migrations) - [ValueObservation] -- [FetchedRecordsController](#fetchedrecordscontroller) -- [RxGRDB](http://github.com/RxSwiftCommunity/RxGRDB) +- [FetchedRecordsController] +- [RxGRDB] Only five types adopt those protocols: DatabaseQueue, DatabasePool, DatabaseSnapshot, AnyDatabaseReader, and AnyDatabaseWriter. Expanding this set is not supported: any future GRDB release may break your custom writers and readers, without notice. @@ -8299,3 +8299,5 @@ This chapter has been renamed [Beyond FetchableRecord]. [Record Customization Options]: #record-customization-options [TableRecord]: #tablerecord-protocol [ValueObservation]: #valueobservation +[FetchedRecordsController]: #fetchedrecordscontroller +[RxGRDB]: http://github.com/RxSwiftCommunity/RxGRDB \ No newline at end of file