From 1201f4e0080c4bc11ce831c4ec7c2cb6c39f2fcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Tue, 10 May 2016 14:16:13 +0200 Subject: [PATCH] FetchedRecordsController: replace delegate with callbacks --- .../GRDBDemoiOS/PersonsViewController.swift | 82 ++-- GRDB/Core/Utils.swift | 13 + GRDB/Record/FetchedRecordsController.swift | 356 +++++++++--------- .../FetchedRecordsControllerTests.swift | 54 ++- 4 files changed, 257 insertions(+), 248 deletions(-) diff --git a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift index de11aca6e..660aa793a 100644 --- a/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift +++ b/DemoApps/GRDBDemoiOS/GRDBDemoiOS/PersonsViewController.swift @@ -14,7 +14,46 @@ class PersonsViewController: UITableViewController { let request = personsSortedByScore personsController = FetchedRecordsController(dbQueue, request: request, compareRecordsByPrimaryKey: true) - personsController.delegate = self + + personsController.willChange { [weak self] _ in + self?.tableView?.beginUpdates() + } + + personsController.onTableViewEvent { [weak self] (controller, record, event) in + guard let strongSelf = self else { + return + } + + switch event { + case .Insertion(let indexPath): + strongSelf.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) + + case .Deletion(let indexPath): + strongSelf.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) + + case .Update(let indexPath, _): + if let cell = strongSelf.tableView.cellForRowAtIndexPath(indexPath) { + strongSelf.configureCell(cell, atIndexPath: indexPath) + } + + case .Move(let indexPath, let newIndexPath, _): + // Actually move cells around for more demo effect :-) + let cell = strongSelf.tableView.cellForRowAtIndexPath(indexPath) + strongSelf.tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath) + if let cell = cell { + strongSelf.configureCell(cell, atIndexPath: newIndexPath) + } + + // A quieter animation: + // strongSelf.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) + // strongSelf.tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade) + } + } + + personsController.didChange { [weak self] _ in + self?.tableView?.endUpdates() + } + personsController.performFetch() configureToolbar() @@ -116,47 +155,6 @@ extension PersonsViewController { } -// MARK: - FetchedRecordsControllerDelegate - -extension PersonsViewController : FetchedRecordsControllerDelegate { - - func controllerWillChangeRecords(controller: FetchedRecordsController) { - tableView.beginUpdates() - } - - func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:FetchedRecordsEvent) { - switch event { - case .Insertion(let indexPath): - tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) - - case .Deletion(let indexPath): - tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) - - case .Update(let indexPath, _): - if let cell = tableView.cellForRowAtIndexPath(indexPath) { - configureCell(cell, atIndexPath: indexPath) - } - - case .Move(let indexPath, let newIndexPath, _): - // Actually move cells around for more demo effect :-) - let cell = tableView.cellForRowAtIndexPath(indexPath) - tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath) - if let cell = cell { - configureCell(cell, atIndexPath: newIndexPath) - } - - // A quieter animation: - // tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) - // tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade) - } - } - - func controllerDidChangeRecords(controller: FetchedRecordsController) { - tableView.endUpdates() - } -} - - // MARK: - FetchedRecordsController Demo extension PersonsViewController { diff --git a/GRDB/Core/Utils.swift b/GRDB/Core/Utils.swift index 6e2428d37..3f34cb3ae 100644 --- a/GRDB/Core/Utils.swift +++ b/GRDB/Core/Utils.swift @@ -106,6 +106,19 @@ extension SequenceType where Generator.Element: Equatable { } } +extension SequenceType { + /// Return true if one element matches the predicate + func any(predicate: (Generator.Element -> Bool)) -> Bool { + for element in self where predicate(element) { return true } + return false + } + + func all(predicate: (Generator.Element -> Bool)) -> Bool { + for element in self where !predicate(element) { return false } + return true + } +} + /// A ReadWriteBox grants multiple readers and single-writer guarantees on a value. final class ReadWriteBox { var value: T { diff --git a/GRDB/Record/FetchedRecordsController.swift b/GRDB/Record/FetchedRecordsController.swift index 8ad05086d..a7a1a7f59 100644 --- a/GRDB/Record/FetchedRecordsController.swift +++ b/GRDB/Record/FetchedRecordsController.swift @@ -251,56 +251,20 @@ public final class FetchedRecordsController { self.fetchedItems = items self.isSameRecord = self.isSameRecordBuilder(db) - if self.delegate != nil { - // Setup a new transaction observer. - let observer = FetchedRecordsObserver( - controller: self, - initialItems: items, - observedTables: statement.sourceTables, - isSameRecord: self.isSameRecord) - self.observer = observer - db.addTransactionObserver(observer) - } + // Setup a new transaction observer. + let observer = FetchedRecordsObserver( + controller: self, + initialItems: items, + observedTables: statement.sourceTables, + isSameRecord: self.isSameRecord) + self.observer = observer + db.addTransactionObserver(observer) } } // MARK: - Configuration - /// The object that is notified when the fetched records changed. - /// - /// If you do not specify a delegate, the controller does not track changes - /// to managed objects associated with its managed object context. - public weak var delegate: FetchedRecordsControllerDelegate? { - didSet { - // Setting the delegate to nil *will* stop database changes - // observation only after last changes are processed, in - // FetchedRecordsObserver.databaseDidCommit. This allows user code - // to change the delegate multiple times: tracking will stop if and - // only if the last delegate value is nil. - // - // Conversely, setting the delegate to a non-nil value must make - // sure that database changes are observed. But only if - // performFetch() has been called. - if let items = fetchedItems where delegate != nil && observer == nil { - // Setup a new transaction observer. Use - // database.write, so that the transaction observer is added on the - // same serialized queue as transaction callbacks. - databaseWriter.write { db in - let statement = try! self.source.selectStatement(db) - let observer = FetchedRecordsObserver( - controller: self, - initialItems: items, - observedTables: statement.sourceTables, - isSameRecord: self.isSameRecordBuilder(db)) - self.observer = observer - db.addTransactionObserver(observer) - observer.checkForChangesInDatabase(db) - } - } - } - } - /// The database writer used to fetch records. /// /// The controller registers as a transaction observer in order to respond @@ -331,6 +295,22 @@ public final class FetchedRecordsController { self.source = DatabaseSource.sql(sql, arguments) } + private var willChangeCallback: (FetchedRecordsController -> ())? + private var didChangeCallback: (FetchedRecordsController -> ())? + private var tableViewEventCallback: ((controller: FetchedRecordsController, record: Record, event: TableViewEvent) -> ())? + + public func willChange(callback: FetchedRecordsController -> ()) { + willChangeCallback = callback + } + + public func didChange(callback: FetchedRecordsController -> ()) { + didChangeCallback = callback + } + + public func onTableViewEvent(callback: (controller: FetchedRecordsController, record: Record, event: TableViewEvent) -> ()) { + tableViewEventCallback = callback + } + // MARK: - Accessing records @@ -412,11 +392,6 @@ public final class FetchedRecordsController { // The eventual current database observer private var observer: FetchedRecordsObserver? - - private func stopTrackingChanges() { - observer?.invalidate() - observer = nil - } } @@ -597,9 +572,20 @@ private final class FetchedRecordsObserver : Transaction // Invalidated? guard let controller = self.controller else { return } - // No changes? - let changes = self.computeChanges(from: self.items, to: fetchedItems) - guard !changes.isEmpty else { return } + // Changes? + let tableViewChanges: [TableViewChange]? + if controller.tableViewEventCallback != nil { + let changes = self.computeTableViewChanges(from: self.items, to: fetchedItems) + guard !changes.isEmpty else { + return + } + tableViewChanges = changes + } else { + guard fetchedItems.count != self.items.count || zip(fetchedItems, self.items).any({ (fetchedItem, item) in fetchedItem.row != item.row }) else { + return + } + tableViewChanges = nil + } // Ready for next check self.items = fetchedItems @@ -608,40 +594,36 @@ private final class FetchedRecordsObserver : Transaction // Invalidated? guard let controller = self.controller else { return } - if let delegate = controller.delegate { - delegate.controllerWillChangeRecords(controller) - controller.fetchedItems = fetchedItems - for change in changes { - delegate.controller(controller, didChangeRecord: change.record, withEvent: change.event) + controller.willChangeCallback?(controller) + controller.fetchedItems = fetchedItems + if let tableViewEventCallback = controller.tableViewEventCallback { + for change in tableViewChanges! { + tableViewEventCallback(controller: controller, record: change.record, event: change.event) } - delegate.controllerDidChangeRecords(controller) - } else { - // There is no delegate interested in changes: stop tracking - // changes. - controller.stopTrackingChanges() } + controller.didChangeCallback?(controller) } } } - func computeChanges(from s: [Item], to t: [Item]) -> [ItemChange] { + func computeTableViewChanges(from s: [Item], to t: [Item]) -> [TableViewChange] { let m = s.count let n = t.count // Fill first row and column of insertions and deletions. - var d: [[[ItemChange]]] = Array(count: m + 1, repeatedValue: Array(count: n + 1, repeatedValue: [])) + var d: [[[TableViewChange]]] = Array(count: m + 1, repeatedValue: Array(count: n + 1, repeatedValue: [])) - var changes = [ItemChange]() + var changes = [TableViewChange]() for (row, item) in s.enumerate() { - let deletion = ItemChange.Deletion(item: item, indexPath: makeIndexPath(forRow: row, inSection: 0)) + let deletion = TableViewChange.Deletion(item: item, indexPath: makeIndexPath(forRow: row, inSection: 0)) changes.append(deletion) d[row + 1][0] = changes } changes.removeAll() for (col, item) in t.enumerate() { - let insertion = ItemChange.Insertion(item: item, indexPath: makeIndexPath(forRow: col, inSection: 0)) + let insertion = TableViewChange.Insertion(item: item, indexPath: makeIndexPath(forRow: col, inSection: 0)) changes.append(insertion) d[0][col + 1] = changes } @@ -664,16 +646,16 @@ private final class FetchedRecordsObserver : Transaction // Record operation. let minimumCount = min(del.count, ins.count, sub.count) if del.count == minimumCount { - let deletion = ItemChange.Deletion(item: s[sx], indexPath: makeIndexPath(forRow: sx, inSection: 0)) + let deletion = TableViewChange.Deletion(item: s[sx], indexPath: makeIndexPath(forRow: sx, inSection: 0)) del.append(deletion) d[sx+1][tx+1] = del } else if ins.count == minimumCount { - let insertion = ItemChange.Insertion(item: t[tx], indexPath: makeIndexPath(forRow: tx, inSection: 0)) + let insertion = TableViewChange.Insertion(item: t[tx], indexPath: makeIndexPath(forRow: tx, inSection: 0)) ins.append(insertion) d[sx+1][tx+1] = ins } else { - let deletion = ItemChange.Deletion(item: s[sx], indexPath: makeIndexPath(forRow: sx, inSection: 0)) - let insertion = ItemChange.Insertion(item: t[tx], indexPath: makeIndexPath(forRow: tx, inSection: 0)) + let deletion = TableViewChange.Deletion(item: s[sx], indexPath: makeIndexPath(forRow: sx, inSection: 0)) + let insertion = TableViewChange.Insertion(item: t[tx], indexPath: makeIndexPath(forRow: tx, inSection: 0)) sub.append(deletion) sub.append(insertion) d[sx+1][tx+1] = sub @@ -683,13 +665,13 @@ private final class FetchedRecordsObserver : Transaction } /// Returns an array where deletion/insertion pairs of the same element are replaced by `.Move` change. - func standardizeChanges(changes: [ItemChange]) -> [ItemChange] { + func standardizeChanges(changes: [TableViewChange]) -> [TableViewChange] { /// Returns a potential .Move or .Update if *change* has a matching change in *changes*: /// If *change* is a deletion or an insertion, and there is a matching inverse /// insertion/deletion with the same value in *changes*, a corresponding .Move or .Update is returned. /// As a convenience, the index of the matched change is returned as well. - func mergedChange(change: ItemChange, inChanges changes: [ItemChange]) -> (mergedChange: ItemChange, mergedIndex: Int)? { + func mergedChange(change: TableViewChange, inChanges changes: [TableViewChange]) -> (mergedChange: TableViewChange, mergedIndex: Int)? { /// Returns the changes between two rows: a dictionary [key: oldValue] /// Precondition: both rows have the same columns @@ -712,9 +694,9 @@ private final class FetchedRecordsObserver : Transaction guard isSameRecord(oldItem.record, newItem.record) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { - return (ItemChange.Update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) + return (TableViewChange.Update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) } else { - return (ItemChange.Move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) + return (TableViewChange.Move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) } } return nil @@ -726,9 +708,9 @@ private final class FetchedRecordsObserver : Transaction guard isSameRecord(oldItem.record, newItem.record) else { continue } let rowChanges = changedValues(from: oldItem.row, to: newItem.row) if oldIndexPath == newIndexPath { - return (ItemChange.Update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) + return (TableViewChange.Update(item: newItem, indexPath: oldIndexPath, changes: rowChanges), index) } else { - return (ItemChange.Move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) + return (TableViewChange.Move(item: newItem, indexPath: oldIndexPath, newIndexPath: newIndexPath, changes: rowChanges), index) } } return nil @@ -739,8 +721,8 @@ private final class FetchedRecordsObserver : Transaction } // Updates must be pushed at the end - var mergedChanges: [ItemChange] = [] - var updateChanges: [ItemChange] = [] + var mergedChanges: [TableViewChange] = [] + var updateChanges: [TableViewChange] = [] for change in changes { if let (mergedChange, mergedIndex) = mergedChange(change, inChanges: mergedChanges) { mergedChanges.removeAtIndex(mergedIndex) @@ -764,106 +746,106 @@ private final class FetchedRecordsObserver : Transaction // MARK: - FetchedRecordsControllerDelegate -/// An instance of FetchedRecordsController uses methods in this protocol to -/// notify its delegate that the controller’s fetched records have been changed -/// due to some add, remove, move, or update operations. -/// -/// -/// # Typical Use -/// -/// You can use controllerWillChangeRecords: and controllerDidChangeRecord: to -/// bracket updates to a table view whose content is provided by the fetched -/// records controller as illustrated in the following example: -/// -/// // Assume self has a tableView property, and a -/// // configureCell(_:atIndexPath:) method which updates the contents of a -/// // given cell. -/// -/// func controllerWillChangeRecords(controller: FetchedRecordsController) { -/// tableView.beginUpdates() -/// } -/// -/// func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:FetchedRecordsEvent) { -/// switch event { -/// case .Insertion(let indexPath): -/// tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) -/// -/// case .Deletion(let indexPath): -/// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) -/// -/// case .Update(let indexPath, _): -/// if let cell = tableView.cellForRowAtIndexPath(indexPath) { -/// configureCell(cell, atIndexPath: indexPath) -/// } -/// -/// case .Move(let indexPath, let newIndexPath, _): -/// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) -/// tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade) -/// -/// // // Alternate technique (which actually moves cells around): -/// // let cell = tableView.cellForRowAtIndexPath(indexPath) -/// // tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath) -/// // if let cell = cell { -/// // configureCell(cell, atIndexPath: newIndexPath) -/// // } -/// } -/// } -/// -/// func controllerDidChangeRecords(controller: FetchedRecordsController) { -/// tableView.endUpdates() -/// } -public protocol FetchedRecordsControllerDelegate : class { - /// Notifies that the fetched records controller is about to start - /// processing of one or more changes due to an add, remove, move, - // or update. - /// - /// - parameter controller: The fetched records controller that sent - /// the message. - func controllerWillChangeRecords(controller: FetchedRecordsController) - - /// Notifies that a record has been changed due to an add, remove, move, - /// or update. - /// - /// Swift mandates the delegate to implement this method as a generic - /// method on the type of the changed record. - /// - /// The advantage is that a single object can be the delegate of multiple - /// fetched records controllers that fetch multiple types of records. The - /// downside is that the actual type of the changed record is erased: you - /// must cast it to the expected type: - /// - /// let personsController: FetchedRecordsController - /// - /// func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:FetchedRecordsEvent) { - /// if controller === personsController { - /// let person = record as! Person // Explicit cast - /// } - /// } - /// - /// - parameters: - /// - controller: The fetched records controller that sent the message. - /// - record: The record that changed. - /// - event: The type of change (see FetchedRecordsEvent). - func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:FetchedRecordsEvent) - - /// Notifies that the fetched records controller has completed processing - /// of one or more changes due to an add, remove, move, or update. - /// - /// - parameter controller: The fetched records controller that sent - /// the message. - func controllerDidChangeRecords(controller: FetchedRecordsController) -} - -public extension FetchedRecordsControllerDelegate { - /// The default implementation does nothing. - func controllerWillChangeRecords(controller: FetchedRecordsController) { } - - /// The default implementation does nothing. - func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:FetchedRecordsEvent) { } - - /// The default implementation does nothing. - func controllerDidChangeRecords(controller: FetchedRecordsController) { } -} +///// An instance of FetchedRecordsController uses methods in this protocol to +///// notify its delegate that the controller’s fetched records have been changed +///// due to some add, remove, move, or update operations. +///// +///// +///// # Typical Use +///// +///// You can use controllerWillChangeRecords: and controllerDidChangeRecord: to +///// bracket updates to a table view whose content is provided by the fetched +///// records controller as illustrated in the following example: +///// +///// // Assume self has a tableView property, and a +///// // configureCell(_:atIndexPath:) method which updates the contents of a +///// // given cell. +///// +///// func controllerWillChangeRecords(controller: FetchedRecordsController) { +///// tableView.beginUpdates() +///// } +///// +///// func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:TableViewEvent) { +///// switch event { +///// case .Insertion(let indexPath): +///// tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) +///// +///// case .Deletion(let indexPath): +///// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) +///// +///// case .Update(let indexPath, _): +///// if let cell = tableView.cellForRowAtIndexPath(indexPath) { +///// configureCell(cell, atIndexPath: indexPath) +///// } +///// +///// case .Move(let indexPath, let newIndexPath, _): +///// tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) +///// tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Fade) +///// +///// // // Alternate technique (which actually moves cells around): +///// // let cell = tableView.cellForRowAtIndexPath(indexPath) +///// // tableView.moveRowAtIndexPath(indexPath, toIndexPath: newIndexPath) +///// // if let cell = cell { +///// // configureCell(cell, atIndexPath: newIndexPath) +///// // } +///// } +///// } +///// +///// func controllerDidChangeRecords(controller: FetchedRecordsController) { +///// tableView.endUpdates() +///// } +//public protocol FetchedRecordsControllerDelegate : class { +// /// Notifies that the fetched records controller is about to start +// /// processing of one or more changes due to an add, remove, move, +// // or update. +// /// +// /// - parameter controller: The fetched records controller that sent +// /// the message. +// func controllerWillChangeRecords(controller: FetchedRecordsController) +// +// /// Notifies that a record has been changed due to an add, remove, move, +// /// or update. +// /// +// /// Swift mandates the delegate to implement this method as a generic +// /// method on the type of the changed record. +// /// +// /// The advantage is that a single object can be the delegate of multiple +// /// fetched records controllers that fetch multiple types of records. The +// /// downside is that the actual type of the changed record is erased: you +// /// must cast it to the expected type: +// /// +// /// let personsController: FetchedRecordsController +// /// +// /// func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:TableViewEvent) { +// /// if controller === personsController { +// /// let person = record as! Person // Explicit cast +// /// } +// /// } +// /// +// /// - parameters: +// /// - controller: The fetched records controller that sent the message. +// /// - record: The record that changed. +// /// - event: The type of change (see TableViewEvent). +// func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:TableViewEvent) +// +// /// Notifies that the fetched records controller has completed processing +// /// of one or more changes due to an add, remove, move, or update. +// /// +// /// - parameter controller: The fetched records controller that sent +// /// the message. +// func controllerDidChangeRecords(controller: FetchedRecordsController) +//} +// +//public extension FetchedRecordsControllerDelegate { +// /// The default implementation does nothing. +// func controllerWillChangeRecords(controller: FetchedRecordsController) { } +// +// /// The default implementation does nothing. +// func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:TableViewEvent) { } +// +// /// The default implementation does nothing. +// func controllerDidChangeRecords(controller: FetchedRecordsController) { } +//} @@ -887,13 +869,13 @@ public struct FetchedRecordsSectionInfo { } -// MARK: - FetchedRecordsEvent +// MARK: - TableViewEvent /// A change event given by a FetchedRecordsController to its delegate. /// /// The move and update events hold a *changes* dictionary. Its keys are column /// names, and values the old values that have been changed. -public enum FetchedRecordsEvent { +public enum TableViewEvent { /// An insertion event, at given indexPath. case Insertion(indexPath: NSIndexPath) @@ -912,7 +894,7 @@ public enum FetchedRecordsEvent { case Update(indexPath: NSIndexPath, changes: [String: DatabaseValue]) } -extension FetchedRecordsEvent: CustomStringConvertible { +extension TableViewEvent: CustomStringConvertible { /// A textual representation of `self`. public var description: String { @@ -977,16 +959,16 @@ private func ==(lhs: Item, rhs: Item) -> Bool { } -// MARK: - ItemChange +// MARK: - TableViewChange -private enum ItemChange { +private enum TableViewChange { case Insertion(item: Item, indexPath: NSIndexPath) case Deletion(item: Item, indexPath: NSIndexPath) case Move(item: Item, indexPath: NSIndexPath, newIndexPath: NSIndexPath, changes: [String: DatabaseValue]) case Update(item: Item, indexPath: NSIndexPath, changes: [String: DatabaseValue]) } -extension ItemChange { +extension TableViewChange { var record: T { switch self { case .Insertion(item: let item, indexPath: _): @@ -1000,7 +982,7 @@ extension ItemChange { } } - var event: FetchedRecordsEvent { + var event: TableViewEvent { switch self { case .Insertion(item: _, indexPath: let indexPath): return .Insertion(indexPath: indexPath) @@ -1014,7 +996,7 @@ extension ItemChange { } } -extension ItemChange: CustomStringConvertible { +extension TableViewChange: CustomStringConvertible { var description: String { switch self { case .Insertion(let item, let indexPath): diff --git a/Tests/Public/FetchedRecordsController/FetchedRecordsControllerTests.swift b/Tests/Public/FetchedRecordsController/FetchedRecordsControllerTests.swift index 59db71bf6..ae049026c 100644 --- a/Tests/Public/FetchedRecordsController/FetchedRecordsControllerTests.swift +++ b/Tests/Public/FetchedRecordsController/FetchedRecordsControllerTests.swift @@ -23,8 +23,8 @@ private func row(for indexPath:NSIndexPath) -> Int { #endif } -private class ChangesRecorder: FetchedRecordsControllerDelegate { - var changes: [(record: Record, event: FetchedRecordsEvent)] = [] +private class ChangesRecorder { + var changes: [(record: Record, event: TableViewEvent)] = [] var recordsBeforeChanges: [Record]! var recordsOnFirstEvent: [Record]! var transactionExpectation: XCTestExpectation? { @@ -35,20 +35,20 @@ private class ChangesRecorder: FetchedRecordsControllerDelegate { } } - func controllerWillChangeRecords(controller: FetchedRecordsController) { - recordsBeforeChanges = controller.fetchedRecords!.map { $0 as! Record } + func controllerWillChange(controller: FetchedRecordsController) { + recordsBeforeChanges = controller.fetchedRecords! } /// The default implementation does nothing. - func controller(controller: FetchedRecordsController, didChangeRecord record: T, withEvent event:FetchedRecordsEvent) { + func controller(controller: FetchedRecordsController, didChangeRecord record: Record, withEvent event:TableViewEvent) { if recordsOnFirstEvent == nil { - recordsOnFirstEvent = controller.fetchedRecords!.map { $0 as! Record } + recordsOnFirstEvent = controller.fetchedRecords! } - changes.append((record: record as! Record, event: event)) + changes.append((record: record, event: event)) } /// The default implementation does nothing. - func controllerDidChangeRecords(controller: FetchedRecordsController) { + func controllerDidChange(controller: FetchedRecordsController) { if let transactionExpectation = transactionExpectation { transactionExpectation.fulfill() } @@ -144,7 +144,9 @@ class FetchedRecordsControllerTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() let controller = FetchedRecordsController(dbQueue, request: Person.order(SQLColumn("id")), compareRecordsByPrimaryKey: true) let recorder = ChangesRecorder() - controller.delegate = recorder + controller.willChange { recorder.controllerWillChange($0) } + controller.didChange { recorder.controllerDidChange($0) } + controller.onTableViewEvent { (controller, record, event) in recorder.controller(controller, didChangeRecord: record, withEvent: event) } controller.performFetch() // First insert @@ -201,7 +203,9 @@ class FetchedRecordsControllerTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() let controller = FetchedRecordsController(dbQueue, request: Person.order(SQLColumn("id")), compareRecordsByPrimaryKey: true) let recorder = ChangesRecorder() - controller.delegate = recorder + controller.willChange { recorder.controllerWillChange($0) } + controller.didChange { recorder.controllerDidChange($0) } + controller.onTableViewEvent { (controller, record, event) in recorder.controller(controller, didChangeRecord: record, withEvent: event) } controller.performFetch() // Insert @@ -277,7 +281,9 @@ class FetchedRecordsControllerTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() let controller = FetchedRecordsController(dbQueue, request: Person.order(SQLColumn("id")), compareRecordsByPrimaryKey: true) let recorder = ChangesRecorder() - controller.delegate = recorder + controller.willChange { recorder.controllerWillChange($0) } + controller.didChange { recorder.controllerDidChange($0) } + controller.onTableViewEvent { (controller, record, event) in recorder.controller(controller, didChangeRecord: record, withEvent: event) } controller.performFetch() // Insert @@ -341,7 +347,9 @@ class FetchedRecordsControllerTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() let controller = FetchedRecordsController(dbQueue, request: Person.order(SQLColumn("name")), compareRecordsByPrimaryKey: true) let recorder = ChangesRecorder() - controller.delegate = recorder + controller.willChange { recorder.controllerWillChange($0) } + controller.didChange { recorder.controllerDidChange($0) } + controller.onTableViewEvent { (controller, record, event) in recorder.controller(controller, didChangeRecord: record, withEvent: event) } controller.performFetch() // Insert @@ -394,7 +402,9 @@ class FetchedRecordsControllerTests: GRDBTestCase { "ORDER BY persons.name"), compareRecordsByPrimaryKey: true) let recorder = ChangesRecorder() - controller.delegate = recorder + controller.willChange { recorder.controllerWillChange($0) } + controller.didChange { recorder.controllerDidChange($0) } + controller.onTableViewEvent { (controller, record, event) in recorder.controller(controller, didChangeRecord: record, withEvent: event) } controller.performFetch() // Insert @@ -439,7 +449,9 @@ class FetchedRecordsControllerTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() let controller = FetchedRecordsController(dbQueue, request: Person.order(SQLColumn("name")), compareRecordsByPrimaryKey: true) let recorder = ChangesRecorder() - controller.delegate = recorder + controller.willChange { recorder.controllerWillChange($0) } + controller.didChange { recorder.controllerDidChange($0) } + controller.onTableViewEvent { (controller, record, event) in recorder.controller(controller, didChangeRecord: record, withEvent: event) } controller.performFetch() enum EventTest { @@ -448,7 +460,7 @@ class FetchedRecordsControllerTests: GRDBTestCase { case D(String, Int) // delete string at index case U(String, Int, String) // update string at index with changed string - func match(name: String, event: FetchedRecordsEvent) -> Bool { + func match(name: String, event: TableViewEvent) -> Bool { switch self { case .I(let s, let i): switch event { @@ -569,7 +581,9 @@ class FetchedRecordsControllerTests: GRDBTestCase { let dbQueue = try makeDatabaseQueue() let controller = FetchedRecordsController(dbQueue, request: Person.order(SQLColumn("name")), compareRecordsByPrimaryKey: true) let recorder = ChangesRecorder() - controller.delegate = recorder + controller.willChange { recorder.controllerWillChange($0) } + controller.didChange { recorder.controllerDidChange($0) } + controller.onTableViewEvent { (controller, record, event) in recorder.controller(controller, didChangeRecord: record, withEvent: event) } controller.performFetch() // Insert @@ -636,7 +650,7 @@ class FetchedRecordsControllerTests: GRDBTestCase { } } - func testSetDelegateAfterUpdate() { + func testSetCallbacksAfterUpdate() { assertNoError { let dbQueue = try makeDatabaseQueue() let controller = FetchedRecordsController(dbQueue, request: Person.order(SQLColumn("name")), compareRecordsByPrimaryKey: true) @@ -650,9 +664,11 @@ class FetchedRecordsControllerTests: GRDBTestCase { return .Commit } - // Set delegate + // Set callbacks recorder.transactionExpectation = expectationWithDescription("expectation") - controller.delegate = recorder + controller.willChange { recorder.controllerWillChange($0) } + controller.didChange { recorder.controllerDidChange($0) } + controller.onTableViewEvent { (controller, record, event) in recorder.controller(controller, didChangeRecord: record, withEvent: event) } waitForExpectationsWithTimeout(1, handler: nil) XCTAssertEqual(recorder.recordsBeforeChanges.count, 0)