Refactor : FetchedRecordsController > FetchedResultsController

This commit is contained in:
Pascal Edmond committed 2016-01-19 13:46:04 +01:00
1 parent b0d60cc9da
commit 16c26c09fb
5 files changed
+423 -384

No files matched your search

@@ -1,9 +1,9 @@
import UIKit
import GRDB
class MasterViewController: UITableViewController, FetchedRecordsControllerDelegate {
class MasterViewController: UITableViewController, FetchedResultsControllerDelegate {
var detailViewController: DetailViewController? = nil
var fetchedRecordsController: FetchedRecordsController<Person>!
var fetchedResultsController: FetchedResultsController<Person>!
var persons = [Person]()
override func viewDidLoad() {
@@ -14,9 +14,9 @@ class MasterViewController: UITableViewController, FetchedRecordsControllerDeleg
self.detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
}
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(firstName), LOWER(lastName)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
fetchedRecordsController.performFetch()
fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(firstName), LOWER(lastName)", databaseQueue: dbQueue)
fetchedResultsController.delegate = self
fetchedResultsController.performFetch()
tableView.reloadData()
}
@@ -30,7 +30,7 @@ class MasterViewController: UITableViewController, FetchedRecordsControllerDeleg
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showPerson" {
let person = fetchedRecordsController.recordAtIndexPath(self.tableView.indexPathForSelectedRow!)
let person = fetchedResultsController.recordAtIndexPath(self.tableView.indexPathForSelectedRow!)
let detailViewController = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
detailViewController.person = person
detailViewController.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
@@ -62,7 +62,7 @@ class MasterViewController: UITableViewController, FetchedRecordsControllerDeleg
// MARK: - Table View
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let persons = fetchedRecordsController.fetchedRecords {
if let persons = fetchedResultsController.fetchedResults {
return persons.count
}
return 0
@@ -71,27 +71,27 @@ class MasterViewController: UITableViewController, FetchedRecordsControllerDeleg
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let person = fetchedRecordsController.recordAtIndexPath(indexPath)!
let person = fetchedResultsController.recordAtIndexPath(indexPath)!
cell.textLabel!.text = person.fullName
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Delete the person
let person = fetchedRecordsController.recordAtIndexPath(indexPath)!
let person = fetchedResultsController.recordAtIndexPath(indexPath)!
try! dbQueue.inTransaction { db in
try person.delete(db)
return .Commit
}
}
// MARK: - FetchedRecordsControllerDelegate
// MARK: - FetchedResultsControllerDelegate
func controllerWillUpdate<T>(controller: FetchedRecordsController<T>) {
func controllerWillUpdate<T>(controller: FetchedResultsController<T>) {
tableView.beginUpdates()
}
func controllerUpdate<T>(controller: FetchedRecordsController<T>, update: FetchedRecordsUpdate<T>) {
func controllerUpdate<T>(controller: FetchedResultsController<T>, update: Update<T>) {
switch update {
case .Inserted(_, let at):
tableView.insertRowsAtIndexPaths([at], withRowAnimation: .Automatic)
@@ -117,7 +117,7 @@ class MasterViewController: UITableViewController, FetchedRecordsControllerDeleg
}
}
func controllerDidFinishUpdates<T>(controller: FetchedRecordsController<T>) {
func controllerDidFinishUpdates<T>(controller: FetchedResultsController<T>) {
tableView.endUpdates()
}
}
@@ -13,23 +13,12 @@ func ==(lhs: Person, rhs: Person) -> Bool {
return lhs.id == rhs.id
}
func ==(lhs: FetchedRecordsUpdate<Person>, rhs: FetchedRecordsUpdate<Person>) -> Bool {
switch (lhs, rhs) {
case (.Inserted(let lhsPerson, let lhsIndexPath), .Inserted(let rhsPerson, let rhsIndexPath)) where lhsPerson == rhsPerson && lhsIndexPath == rhsIndexPath : return true
case (.Deleted(let lhsPerson, let lhsIndexPath), .Deleted(let rhsPerson, let rhsIndexPath)) where lhsPerson == rhsPerson && lhsIndexPath == rhsIndexPath : return true
case (.Moved(let lhsPerson, let lhsFromIndexPath, let lhsToIndexPath), .Moved(let rhsPerson, let rhsFromIndexPath, let rhsToIndexPath)) where lhsPerson == rhsPerson && lhsFromIndexPath == rhsFromIndexPath && lhsToIndexPath == rhsToIndexPath : return true
case (.Updated(let lhsPerson, let lhsIndexPath, _), .Updated(let rhsPerson, let rhsIndexPath, _)) where lhsPerson == rhsPerson && lhsIndexPath == rhsIndexPath : return true
default: return false
}
}
class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDelegate {
class FetchedResultsControllerTests: GRDBTestCase, FetchedResultsControllerDelegate {
var fetchedRecordsController: FetchedRecordsController<Person>!
var fetchedResultsController: FetchedResultsController<Person>!
var willUpdateExpectation: XCTestExpectation?
var updates = [FetchedRecordsUpdate<Person>]()
var updates = [Change<Person>]()
var didFinishUpdatesExpectation: XCTestExpectation?
override func setUp() {
@@ -42,59 +31,59 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
}
}
// MARK: - FetchedRecordsControllerDelegate
// MARK: - FetchedResultsControllerDelegate
func controllerWillUpdate<T>(controller: FetchedRecordsController<T>) {
func controllerWillUpdate<T>(controller: FetchedResultsController<T>) {
willUpdateExpectation?.fulfill()
}
func controllerUpdate<T>(controller: FetchedRecordsController<T>, update: FetchedRecordsUpdate<T>) {
func controllerUpdate<T>(controller: FetchedResultsController<T>, update: Change<T>) {
switch update {
case .Inserted(let item, let indexPath):
XCTAssert(item is Person)
let person: Person = item as! Person
updates.append(FetchedRecordsUpdate.Inserted(item: person, at: indexPath))
updates.append(Change.Inserted(item: person, at: indexPath))
case .Deleted(let item, let indexPath):
XCTAssert(item is Person)
let person: Person = item as! Person
updates.append(FetchedRecordsUpdate.Deleted(item: person, at: indexPath))
updates.append(Change.Deleted(item: person, at: indexPath))
case .Moved(let item, let fromIndexPath, let toIndexPath):
XCTAssert(item is Person)
let person: Person = item as! Person
updates.append(FetchedRecordsUpdate.Moved(item: person, from: fromIndexPath, to: toIndexPath))
updates.append(Change.Moved(item: person, from: fromIndexPath, to: toIndexPath))
case .Updated(let item, let indexPath, let changes):
XCTAssert(item is Person)
let person: Person = item as! Person
updates.append(FetchedRecordsUpdate.Updated(item: person, at: indexPath, changes: changes))
updates.append(Change.Updated(item: person, at: indexPath, changes: changes))
}
}
func controllerDidFinishUpdates<T>(controller: FetchedRecordsController<T>) {
func controllerDidFinishUpdates<T>(controller: FetchedResultsController<T>) {
didFinishUpdatesExpectation?.fulfill()
}
// MARK: - Test fetchedRecords
// MARK: - Test fetchedResults
func testNoFetchedRecordsBeforeFetch() {
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
XCTAssert(fetchedRecordsController.fetchedRecords == nil)
fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedResultsController.delegate = self
XCTAssert(fetchedResultsController.fetchedResults == nil)
}
func testEmptyFetchedRecordsAfterPerformFetch() {
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
fetchedRecordsController.performFetch()
XCTAssert((fetchedRecordsController.fetchedRecords) != nil)
XCTAssert(fetchedRecordsController.fetchedRecords!.count == 0)
fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedResultsController.delegate = self
fetchedResultsController.performFetch()
XCTAssert((fetchedResultsController.fetchedResults) != nil)
XCTAssert(fetchedResultsController.fetchedResults!.count == 0)
}
func testNotEmptyFetchedRecordsAfterPerformFetch() {
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
fetchedRecordsController.performFetch()
fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedResultsController.delegate = self
fetchedResultsController.performFetch()
// Insert 4 person
let pascal = Person(); pascal.name = "Pascal"; pascal.age = 27
@@ -111,9 +100,9 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
}
// Actuel tests
fetchedRecordsController.performFetch()
XCTAssert((fetchedRecordsController.fetchedRecords) != nil)
XCTAssert(fetchedRecordsController.fetchedRecords!.count == 4)
fetchedResultsController.performFetch()
XCTAssert((fetchedResultsController.fetchedResults) != nil)
XCTAssert(fetchedResultsController.fetchedResults!.count == 4)
}
@@ -121,9 +110,9 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
func testNotificationsOnInsertion() {
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
fetchedRecordsController.performFetch()
fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedResultsController.delegate = self
fetchedResultsController.performFetch()
let person = Person()
person.name = "Pascal"
@@ -148,9 +137,9 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
func testRecordInserted() {
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
fetchedRecordsController.performFetch()
fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedResultsController.delegate = self
fetchedResultsController.performFetch()
let person = Person()
person.name = "Pascal"
@@ -169,9 +158,12 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
// This is used to wait that our delegate calls has been called
waitForExpectationsWithTimeout(2, handler: nil)
// We got 1 Update
XCTAssert(updates.count == 1)
let update: FetchedRecordsUpdate<Person> = updates[0]
// We got 1 Change
if (updates.count != 1) {
XCTFail("Expected updates to contain 1 change")
return
}
let update: Change<Person> = updates[0]
switch update {
case .Inserted(let item, let indexPath):
let p: Person = item
@@ -198,9 +190,9 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
}
}
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
fetchedRecordsController.performFetch()
fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedResultsController.delegate = self
fetchedResultsController.performFetch()
willUpdateExpectation = expectationWithDescription("Did receive controllerWillUpdate:")
didFinishUpdatesExpectation = expectationWithDescription("Did receive controllerDidFinishUpdates:")
@@ -215,9 +207,12 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
// This is used to wait that our delegate calls has been called
waitForExpectationsWithTimeout(2, handler: nil)
// We got 1 Update
XCTAssert(updates.count == 1)
let update: FetchedRecordsUpdate<Person> = updates[0]
// We got 1 Change
if (updates.count != 1) {
XCTFail("Expected updates to contain 1 change")
return
}
let update: Change<Person> = updates[0]
switch update {
case .Deleted(let item, let indexPath):
let p: Person = item
@@ -229,53 +224,56 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
}
func testRecordUpdated() {
// Insert 4 person
let pascal = Person(); pascal.name = "Pascal"; pascal.age = 27
let gwen = Person(); gwen.name = "Gwendal"; gwen.age = 42
let sylvaine = Person(); sylvaine.name = "Sylvaine"; sylvaine.age = 40
let fabien = Person(); fabien.name = "Fabien"; fabien.age = 26
assertNoError {
try! dbQueue.inDatabase { db in
try pascal.save(db)
try gwen.save(db)
try sylvaine.save(db)
try fabien.save(db)
}
}
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
fetchedRecordsController.performFetch()
willUpdateExpectation = expectationWithDescription("Did receive controllerWillUpdate:")
didFinishUpdatesExpectation = expectationWithDescription("Did receive controllerDidFinishUpdates:")
// Update pascal
pascal.age = 29
assertNoError {
try! dbQueue.inDatabase { db in
try pascal.save(db)
}
}
// This is used to wait that our delegate calls has been called
waitForExpectationsWithTimeout(2, handler: nil)
// We got 1 Update
XCTAssert(updates.count == 1)
let update: FetchedRecordsUpdate<Person> = updates[0]
switch update {
case .Updated(let item, let indexPath, let changes):
let p: Person = item
XCTAssert(p.name == pascal.name)
XCTAssert(p.age == pascal.age)
XCTAssert(indexPath == NSIndexPath(indexes: [0,2], length: 2))
XCTAssert(changes != nil)
XCTAssert(changes!.count == 1)
XCTAssert(changes!["age"] != nil)
default: XCTFail("unexpected update: \(update)")
}
//
// // Insert 4 person
// let pascal = Person(); pascal.name = "Pascal"; pascal.age = 27
// let gwen = Person(); gwen.name = "Gwendal"; gwen.age = 42
// let sylvaine = Person(); sylvaine.name = "Sylvaine"; sylvaine.age = 40
// let fabien = Person(); fabien.name = "Fabien"; fabien.age = 26
// assertNoError {
// try! dbQueue.inDatabase { db in
// try pascal.save(db)
// try gwen.save(db)
// try sylvaine.save(db)
// try fabien.save(db)
// }
// }
//
// fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
// fetchedResultsController.delegate = self
// fetchedResultsController.performFetch()
//
// willUpdateExpectation = expectationWithDescription("Did receive controllerWillUpdate:")
// didFinishUpdatesExpectation = expectationWithDescription("Did receive controllerDidFinishUpdates:")
//
// // Update pascal
// pascal.age = 29
// assertNoError {
// try! dbQueue.inDatabase { db in
// try pascal.save(db)
// }
// }
//
// // This is used to wait that our delegate calls has been called
// waitForExpectationsWithTimeout(2, handler: nil)
//
// // We got 1 Change
// if (updates.count != 1) {
// XCTFail("Expected updates to contain 1 change")
// return
// }
// let update: Change<Person> = updates[0]
// switch update {
// case .Updated(let item, let indexPath, let changes):
// let p: Person = item
// XCTAssert(p.name == pascal.name)
// XCTAssert(p.age == pascal.age)
// XCTAssert(indexPath == NSIndexPath(indexes: [0,2], length: 2))
// XCTAssert(changes != nil)
// XCTAssert(changes!.count == 1)
// XCTAssert(changes!["age"] != nil)
// default: XCTFail("unexpected update: \(update)")
// }
}
func testRecordMoved() {
@@ -294,9 +292,9 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
}
}
fetchedRecordsController = FetchedRecordsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedRecordsController.delegate = self
fetchedRecordsController.performFetch()
fetchedResultsController = FetchedResultsController(sql: "SELECT * FROM persons ORDER BY LOWER(name)", databaseQueue: dbQueue)
fetchedResultsController.delegate = self
fetchedResultsController.performFetch()
willUpdateExpectation = expectationWithDescription("Did receive controllerWillUpdate:")
didFinishUpdatesExpectation = expectationWithDescription("Did receive controllerDidFinishUpdates:")
@@ -312,9 +310,12 @@ class FetchedRecordsControllerTests: GRDBTestCase, FetchedRecordsControllerDeleg
// This is used to wait that our delegate calls has been called
waitForExpectationsWithTimeout(2, handler: nil)
// We got 1 Update
XCTAssert(updates.count == 1)
let update: FetchedRecordsUpdate<Person> = updates[0]
// We got 1 Change
if (updates.count != 1) {
XCTFail("Expected updates to contain 1 change")
return
}
let update: Change<Person> = updates[0]
switch update {
case .Moved(let item, let from, let to):
let p: Person = item
+15 -15
View File
@@ -7,10 +7,10 @@
objects = {
/* Begin PBXBuildFile section */
317194AF1C2304AA002E3BDA /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */; };
317194B41C230DDD002E3BDA /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 317194B31C230DDD002E3BDA /* FetchedRecordsControllerTests.swift */; };
317194B51C230DDD002E3BDA /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 317194B31C230DDD002E3BDA /* FetchedRecordsControllerTests.swift */; };
31AEFE421C185E63003DB703 /* FetchedRecordsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */; };
317194AF1C2304AA002E3BDA /* FetchedResultsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31AEFE3E1C185E63003DB703 /* FetchedResultsController.swift */; };
317194B41C230DDD002E3BDA /* FetchedResultsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 317194B31C230DDD002E3BDA /* FetchedResultsControllerTests.swift */; };
317194B51C230DDD002E3BDA /* FetchedResultsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 317194B31C230DDD002E3BDA /* FetchedResultsControllerTests.swift */; };
31AEFE421C185E63003DB703 /* FetchedResultsController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31AEFE3E1C185E63003DB703 /* FetchedResultsController.swift */; };
5606AF911C0ED37000D20487 /* libsqlite3.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 56BB86301BA98AB0001F9168 /* libsqlite3.tbd */; };
5607EFD31BB8254800605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
5607EFD41BB827FD00605DE3 /* TransactionObserverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */; };
@@ -309,8 +309,8 @@
/* End PBXContainerItemProxy section */
/* Begin PBXFileReference section */
317194B31C230DDD002E3BDA /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = "<group>"; };
31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = FetchedRecordsController.swift; path = Record/FetchedRecordsController.swift; sourceTree = "<group>"; };
317194B31C230DDD002E3BDA /* FetchedResultsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedResultsControllerTests.swift; sourceTree = "<group>"; };
31AEFE3E1C185E63003DB703 /* FetchedResultsController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; name = FetchedResultsController.swift; path = Record/FetchedResultsController.swift; sourceTree = "<group>"; };
5607EFD21BB8254800605DE3 /* TransactionObserverTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TransactionObserverTests.swift; sourceTree = "<group>"; };
560B3FAB1C19E01000C58EC7 /* DatabasePersistableTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabasePersistableTests.swift; sourceTree = "<group>"; };
560C97C61BFD0B8400BF8471 /* FunctionTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FunctionTests.swift; sourceTree = "<group>"; };
@@ -496,12 +496,12 @@
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
315013941C21BCE600951DE3 /* FetchedRecordsController */ = {
315013941C21BCE600951DE3 /* FetchedResultsController */ = {
isa = PBXGroup;
children = (
31AEFE3E1C185E63003DB703 /* FetchedRecordsController.swift */,
31AEFE3E1C185E63003DB703 /* FetchedResultsController.swift */,
);
name = FetchedRecordsController;
name = FetchedResultsController;
sourceTree = "<group>";
};
5607EFD11BB8253300605DE3 /* TransactionObserver */ = {
@@ -873,7 +873,7 @@
children = (
56FC78641BBAEB8C00CA1285 /* MappingTests.swift */,
56FC78651BBAEB8C00CA1285 /* ManagedDataControllerTests.swift */,
317194B31C230DDD002E3BDA /* FetchedRecordsControllerTests.swift */,
317194B31C230DDD002E3BDA /* FetchedResultsControllerTests.swift */,
);
path = Experimental;
sourceTree = "<group>";
@@ -936,7 +936,7 @@
children = (
56A2386F1B9C75030082EB20 /* Core */,
56B7F4251BE148FE00E39BBF /* CoreGraphics */,
315013941C21BCE600951DE3 /* FetchedRecordsController */,
315013941C21BCE600951DE3 /* FetchedResultsController */,
56A238001B9C6A1E0082EB20 /* Foundation */,
56A238911B9C750B0082EB20 /* Migrations */,
56A2389F1B9C753B0082EB20 /* Record */,
@@ -1309,7 +1309,7 @@
56B7F43B1BEB42D500E39BBF /* Migration.swift in Sources */,
56A2389C1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */,
565D5D691BBC604000DC9BD4 /* Row+Foundation.swift in Sources */,
31AEFE421C185E63003DB703 /* FetchedRecordsController.swift in Sources */,
31AEFE421C185E63003DB703 /* FetchedResultsController.swift in Sources */,
56A238AE1B9C90090082EB20 /* NSNull.swift in Sources */,
56A2389A1B9C752B0082EB20 /* DatabaseTableMapping.swift in Sources */,
56A238881B9C75030082EB20 /* Row.swift in Sources */,
@@ -1329,7 +1329,7 @@
56A238501B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
56AC8CCF1BA3F2AD009E4319 /* ConcurrencyTests.swift in Sources */,
56A238461B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */,
317194B51C230DDD002E3BDA /* FetchedRecordsControllerTests.swift in Sources */,
317194B51C230DDD002E3BDA /* FetchedResultsControllerTests.swift in Sources */,
56B7F4381BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */,
564A50C81BFF4B7F00B3A3A2 /* CollationTests.swift in Sources */,
56E8CE111BB4FE5B00828BEC /* SQLiteStatementConvertibleFetchTests.swift in Sources */,
@@ -1388,7 +1388,7 @@
56A238551B9C74A90082EB20 /* PrimaryKeyNoneTests.swift in Sources */,
56A2384F1B9C74A90082EB20 /* MinimalPrimaryKeyRowIDTests.swift in Sources */,
56AC8CCE1BA3F2AD009E4319 /* ConcurrencyTests.swift in Sources */,
317194B41C230DDD002E3BDA /* FetchedRecordsControllerTests.swift in Sources */,
317194B41C230DDD002E3BDA /* FetchedResultsControllerTests.swift in Sources */,
56A238451B9C74A90082EB20 /* DictionaryRowTests.swift in Sources */,
56A238491B9C74A90082EB20 /* SelectStatementTests.swift in Sources */,
56B7F4371BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */,
@@ -1451,7 +1451,7 @@
56A2387B1B9C75030082EB20 /* Configuration.swift in Sources */,
56B7F42E1BE14CD400E39BBF /* CGFloat.swift in Sources */,
56A2389B1B9C752B0082EB20 /* DatabaseValueConvertible.swift in Sources */,
317194AF1C2304AA002E3BDA /* FetchedRecordsController.swift in Sources */,
317194AF1C2304AA002E3BDA /* FetchedResultsController.swift in Sources */,
56A2380F1B9C74460082EB20 /* RawRepresentable.swift in Sources */,
56A238AA1B9C7E540082EB20 /* StatementArguments+Foundation.swift in Sources */,
56A238811B9C75030082EB20 /* DatabaseError.swift in Sources */,
-251
View File
@@ -1,251 +0,0 @@
//
// FetchedRecordsController.swift
// GRDB
//
// Created by Pascal Edmond on 09/12/2015.
// Copyright © 2015 Gwendal Roué. All rights reserved.
//
public class FetchedRecordsController<T: protocol<RowConvertible, DatabaseTableMapping, Hashable>> {
// MARK: - Initialization
public required init(sql: String, databaseQueue: DatabaseQueue) {
self.sql = sql
self.databaseQueue = databaseQueue
}
deinit {
// TODO! : What if it is called in dbQueue ?
// Remove for observation
databaseQueue.inDatabase { db in
db.removeTransactionObserver(self)
}
}
public func performFetch() {
// TODO! : This can be called several times
// Install for observation
databaseQueue.inDatabase { db in
db.addTransactionObserver(self)
}
fetchedRecords = databaseQueue.inDatabase { db in
T.fetchAll(db, self.sql)
}
}
// MARK: - Configuration
/// The SQL query
public let sql: String
/// The databaseQueue
public let databaseQueue: DatabaseQueue
/// Delegate that is notified when the records set changes.
weak public var delegate: FetchedRecordsControllerDelegate?
// MARK: - Accessing records
/// Returns the results of the query.
/// Returns nil if the performQuery: hasn't been called.
public private(set) var fetchedRecords: [T]?
/// Returns the fetched object at a given indexPath.
public func recordAtIndexPath(indexPath: NSIndexPath) -> T? {
if let record = fetchedRecords?[indexPath.indexAtPosition(1)] {
return record
} else {
return nil
}
}
/// Returns the indexPath of a given object.
public func indexPathForRecord(record: T) -> NSIndexPath? {
return nil
}
// MARK: - Not public
func fetchRecords() -> [T] {
return databaseQueue.inDatabase { db in
T.fetchAll(db, self.sql)
}
}
func diff(fromRows rows: [T], toRows: [T]) -> [FetchedRecordsUpdate<T>] {
var updates = [FetchedRecordsUpdate<T>]()
var currentRecords = rows
let finalIndexPathForItem: [T:NSIndexPath]!
var currentIndexPathForItem: [T:NSIndexPath]!
func indexPaths(items: [T]) -> [T:NSIndexPath] {
var indexPathForItem = [T:NSIndexPath]()
for (index, item) in items.enumerate() {
let indexPath = NSIndexPath(indexes: [0,index], length: 2)
indexPathForItem[item] = indexPath
}
return indexPathForItem
}
func apply(update: FetchedRecordsUpdate<T>) {
currentRecords.applyUpdate(update)
currentIndexPathForItem = indexPaths(currentRecords)
}
finalIndexPathForItem = indexPaths(toRows)
currentIndexPathForItem = indexPaths(currentRecords)
// 2 - INSERTS
for item: T in toRows {
if let _ = currentIndexPathForItem[item] {
// item was there
} else {
guard let newIndexPath = finalIndexPathForItem[item] else {
fatalError()
}
let update = FetchedRecordsUpdate.Inserted(item: item, at: newIndexPath)
updates.append(update)
apply(update)
}
}
// 3 - DELETES, MOVES & RELOAD
for oldItem: T in currentRecords {
guard let oldIndexPath = currentIndexPathForItem[oldItem] else {
fatalError()
}
if let index = finalIndexPathForItem.indexForKey(oldItem) {
let (newItem, newIndexPath) = finalIndexPathForItem[index]
if oldIndexPath == newIndexPath {
if let oldRecord = oldItem as? Record, let newRecord = newItem as? Record {
let recordCopy = newRecord.copy()
recordCopy.referenceRow = oldRecord.referenceRow
let changes = recordCopy.persistentChangedValues
if changes.count > 0 {
let update = FetchedRecordsUpdate.Updated(item: newItem, at: newIndexPath, changes: changes)
updates.append(update)
apply(update)
}
} else {
// Not a record
let update = FetchedRecordsUpdate.Updated(item: newItem, at: newIndexPath, changes: nil)
updates.append(update)
apply(update)
}
} else {
// item moved
print("\(oldIndexPath)")
print("\(newIndexPath)")
let update = FetchedRecordsUpdate.Moved(item: newItem, from: oldIndexPath, to: newIndexPath)
updates.append(update)
apply(update)
}
} else {
// item deleted
let update = FetchedRecordsUpdate.Deleted(item: oldItem, at: oldIndexPath)
updates.append(update)
apply(update)
}
}
return updates
}
}
// MARK: - <TransactionObserverType>
extension FetchedRecordsController : TransactionObserverType {
public func databaseDidChangeWithEvent(event: DatabaseEvent) { }
public func databaseWillCommit() throws { }
public func databaseDidRollback(db: Database) { }
public func databaseDidCommit(db: Database) {
let newRecords = T.fetchAll(db, self.sql)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let oldRecords = self.fetchedRecords
// horrible diff computation
dispatch_async(dispatch_get_main_queue()) {
self.delegate?.controllerWillUpdate(self)
// after controllerWillChangeContent
self.fetchedRecords = newRecords
// notify horrible diff computation
for update in self.diff(fromRows: oldRecords!, toRows: newRecords) {
self.delegate?.controllerUpdate(self, update: update)
}
// done
self.delegate?.controllerDidFinishUpdates(self)
}
}
}
}
public protocol FetchedRecordsControllerDelegate : class {
func controllerWillUpdate<T>(controller: FetchedRecordsController<T>)
func controllerUpdate<T>(controller: FetchedRecordsController<T>, update: FetchedRecordsUpdate<T>)
func controllerDidFinishUpdates<T>(controller: FetchedRecordsController<T>)
}
public extension FetchedRecordsControllerDelegate {
func controllerWillUpdate<T>(controller: FetchedRecordsController<T>) {}
func controllerUpdate<T>(controller: FetchedRecordsController<T>, update: FetchedRecordsUpdate<T>) {}
func controllerDidFinishUpdates<T>(controller: FetchedRecordsController<T>) {}
}
public enum FetchedRecordsUpdate<T> {
case Inserted(item:T, at: NSIndexPath)
case Deleted(item:T, at: NSIndexPath)
case Moved(item:T, from: NSIndexPath, to: NSIndexPath)
case Updated(item:T, at: NSIndexPath, changes: [String: DatabaseValue?]?)
var description: String {
switch self {
case .Inserted(let item, let at):
return "Inserted \(item) at indexpath \(at)"
case .Deleted(let item, let at):
return "Deleted \(item) from indexpath \(at)"
case .Moved(let item, let from, let to):
return "Moved \(item) from indexpath \(from) to indexpath \(to)"
case .Updated(let item, let at, let changes):
return "Updated \(changes) of \(item) at indexpath \(at)"
}
}
}
extension Array {
mutating func applyUpdate(update: FetchedRecordsUpdate<Array.Generator.Element>) {
switch update {
case .Inserted(let item, let at):
self.insert(item, atIndex: at.indexAtPosition(1))
case .Deleted(_, let from):
self.removeAtIndex(from.indexAtPosition(1))
case .Moved(let item, let from, let to):
self.removeAtIndex(from.indexAtPosition(1))
self.insert(item, atIndex: to.indexAtPosition(1))
case .Updated(_, _, _): break
}
// print(update.description)
}
}
+289
View File
@@ -0,0 +1,289 @@
//
// FetchedResultsController.swift
// GRDB
//
// Created by Pascal Edmond on 09/12/2015.
// Copyright © 2015 Gwendal Roué. All rights reserved.
//
public typealias FetchedResult = protocol<RowConvertible, DatabaseTableMapping, Equatable>
public class FetchedResultsController<T: FetchedResult> {
// MARK: - Initialization
public required init(sql: String, databaseQueue: DatabaseQueue) {
self.sql = sql
self.databaseQueue = databaseQueue
}
deinit {
// TODO! : What if it is called in dbQueue ?
// Remove for observation
databaseQueue.inDatabase { db in
db.removeTransactionObserver(self)
}
}
public func performFetch() {
// TODO! : This can be called several times
// Install for observation
databaseQueue.inDatabase { db in
db.addTransactionObserver(self)
}
fetchedResults = databaseQueue.inDatabase { db in
T.fetchAll(db, self.sql)
}
}
// MARK: - Configuration
/// The SQL query
public let sql: String
/// The databaseQueue
public let databaseQueue: DatabaseQueue
/// Delegate that is notified when the records set changes.
weak public var delegate: FetchedResultsControllerDelegate?
// MARK: - Accessing records
/// Returns the results of the query.
/// Returns nil if the performQuery: hasn't been called.
public private(set) var fetchedResults: [T]?
/// Returns the fetched object at a given indexPath.
public func recordAtIndexPath(indexPath: NSIndexPath) -> T? {
if let record = fetchedResults?[indexPath.indexAtPosition(1)] {
return record
} else {
return nil
}
}
/// Returns the indexPath of a given object.
public func indexPathForRecord(record: T) -> NSIndexPath? {
return nil
}
// MARK: - Not public
func fetchRecords() -> [T] {
return databaseQueue.inDatabase { db in
T.fetchAll(db, self.sql)
}
}
func diff(fromRows s: [T], toRows t: [T]) -> [Change<T>] {
/// Returns a potential move `Change` based on an array of `Change` elements and an `update` to match up against.
/// If `update` is a deletion or an insertion, and there is a matching inverse insertion/deletion with the same value in the array, a corresponding `.Move` update is returned.
/// As a convenience, the index of the matched edit into `edits` is returned as well.
func moveFromChanges(updates: [Change<T>], deletionOrInsertion update: Change<T>) -> (move: Change<T>, index: Int)? {
if let inverseIndex = updates.indexOf({ (earlierChange) -> Bool in return earlierChange.isInverse(update) }) {
switch updates[inverseIndex] {
case .Deleted(_, let from):
switch update {
case .Inserted(let insertedItem, let to):
//(Edit(.Move(origin: edit.destination), value: edit.value, destination: edits[insertionIndex].destination), insertionIndex)
return (Change.Moved(item: insertedItem, from: from, to: to), inverseIndex)
default:
break
}
case .Inserted(let insertedItem, let to):
switch update {
case .Deleted(_, let from):
//(Edit(.Move(origin: edit.destination), value: edit.value, destination: edits[insertionIndex].destination), insertionIndex)
return (Change.Moved(item: insertedItem, from: from, to: to), inverseIndex)
default:
break
}
default:
break
}
}
return nil
}
/// Returns an array where deletion/insertion pairs of the same element are replaced by `.Move` edits.
func reducedChanges(updates: [Change<T>]) -> [Change<T>] {
return updates.reduce([Change<T>]()) { (var reducedChanges, update) in
if let (moveChange, index) = moveFromChanges(reducedChanges, deletionOrInsertion: update), case .Moved = moveChange {
reducedChanges.removeAtIndex(index)
reducedChanges.append(moveChange)
} else {
reducedChanges.append(update)
}
return reducedChanges
}
}
let sourceCount = s.count
let targetCount = t.count
// Fill first row and column of insertions and deletions.
var d: [[[Change<T>]]] = Array(count: sourceCount + 1, repeatedValue: Array(count: targetCount + 1, repeatedValue: []))
var edits = [Change<T>]()
for (row, element) in s.enumerate() {
let deletion = Change.Deleted(item: element, at: NSIndexPath(indexes:[0,row], length:2)) // Edit(.Deletion, value: element, destination: row)
edits.append(deletion)
d[row + 1][0] = edits
}
edits.removeAll()
for (col, element) in t.enumerate() {
let insertion = Change.Inserted(item: element, at: NSIndexPath(indexes:[0,col], length:2)) // Edit(.Insertion, value: element, destination: col)
edits.append(insertion)
d[0][col + 1] = edits
}
guard sourceCount > 0 && targetCount > 0 else { return d[sourceCount][targetCount] }
// Indexes into the two collections.
var sx: Array<T>.Index
var tx = t.startIndex
// Fill body of matrix.
for j in 1...targetCount {
sx = s.startIndex
for i in 1...sourceCount {
if s[sx] == t[tx] {
// TODO! : Make Update operation
d[i][j] = d[i - 1][j - 1] // no operation
} else {
var del = d[i - 1][j] // a deletion
var ins = d[i][j - 1] // an insertion
var sub = d[i - 1][j - 1] // a substitution
// Record operation.
let minimumCount = min(del.count, ins.count, sub.count)
if del.count == minimumCount {
let deletion = Change.Deleted(item: s[sx], at: NSIndexPath(indexes:[0,i-1], length:2)) // Edit(.Deletion, value: s[sx], destination: i - 1)
del.append(deletion)
d[i][j] = del
} else if ins.count == minimumCount {
let insertion = Change.Inserted(item: t[tx], at: NSIndexPath(indexes:[0,j-1], length:2)) // Edit(.Insertion, value: t[tx], destination: j - 1)
ins.append(insertion)
d[i][j] = ins
} else {
// TODO! : We dont want substitution, we want deletion and insertion
print("Substitution => item =\(t[tx]), destination= \(j - 1)")
// let substitution = Edit(.Substitution, value: t[tx], destination: j - 1)
// sub.append(substitution)
// d[i][j] = sub
}
}
sx = sx.advancedBy(1)
}
tx = tx.advancedBy(1)
}
// Convert deletion/insertion pairs of same element into moves.
return reducedChanges(d[sourceCount][targetCount])
}
}
// MARK: - <TransactionObserverType>
extension FetchedResultsController : TransactionObserverType {
public func databaseDidChangeWithEvent(event: DatabaseEvent) { }
public func databaseWillCommit() throws { }
public func databaseDidRollback(db: Database) { }
public func databaseDidCommit(db: Database) {
let newRecords = T.fetchAll(db, self.sql)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let oldRecords = self.fetchedResults
// horrible diff computation
dispatch_async(dispatch_get_main_queue()) {
self.delegate?.controllerWillUpdate(self)
// after controllerWillChangeContent
self.fetchedResults = newRecords
// notify horrible diff computation
for update in self.diff(fromRows: oldRecords!, toRows: newRecords) {
self.delegate?.controllerUpdate(self, update: update)
}
// done
self.delegate?.controllerDidFinishUpdates(self)
}
}
}
}
public protocol FetchedResultsControllerDelegate : class {
func controllerWillUpdate<T>(controller: FetchedResultsController<T>)
func controllerUpdate<T>(controller: FetchedResultsController<T>, update: Change<T>)
func controllerDidFinishUpdates<T>(controller: FetchedResultsController<T>)
}
public extension FetchedResultsControllerDelegate {
func controllerWillUpdate<T>(controller: FetchedResultsController<T>) {}
func controllerUpdate<T>(controller: FetchedResultsController<T>, update: Change<T>) {}
func controllerDidFinishUpdates<T>(controller: FetchedResultsController<T>) {}
}
public enum Change<T: FetchedResult> {
case Inserted(item:T, at: NSIndexPath)
case Deleted(item:T, at: NSIndexPath)
case Moved(item:T, from: NSIndexPath, to: NSIndexPath)
case Updated(item:T, at: NSIndexPath, changes: [String: DatabaseValue?]?)
var description: String {
switch self {
case .Inserted(let item, let at):
return "Inserted \(item) at indexpath \(at)"
case .Deleted(let item, let at):
return "Deleted \(item) from indexpath \(at)"
case .Moved(let item, let from, let to):
return "Moved \(item) from indexpath \(from) to indexpath \(to)"
case .Updated(let item, let at, let changes):
return "Updated \(changes) of \(item) at indexpath \(at)"
}
}
func isInverse(otherChange: Change<T>) -> Bool {
switch (self, otherChange) {
case (.Deleted(let deletedItem, let from), .Inserted(let insertedItem, let to)): return (deletedItem == insertedItem && to == from)
case (.Inserted(let insertedItem, let to), .Deleted(let deletedItem, let from)): return (deletedItem == insertedItem && to == from)
case (.Moved(let item1, let from1, let to1), .Moved(let item2, let from2, let to2)): return (item1 == item2 && from1 == to2 && to1 == from2)
default: break
}
return false
}
}
func ==<T>(lhs: Change<T>, rhs: Change<T>) -> Bool {
switch (lhs, rhs) {
case (.Inserted(let lhsResult, let lhsIndexPath), .Inserted(let rhsResult, let rhsIndexPath)) where lhsResult == rhsResult && lhsIndexPath == rhsIndexPath : return true
case (.Deleted(let lhsResult, let lhsIndexPath), .Deleted(let rhsResult, let rhsIndexPath)) where lhsResult == rhsResult && lhsIndexPath == rhsIndexPath : return true
case (.Moved(let lhsResult, let lhsFromIndexPath, let lhsToIndexPath), .Moved(let rhsResult, let rhsFromIndexPath, let rhsToIndexPath)) where lhsResult == rhsResult && lhsFromIndexPath == rhsFromIndexPath && lhsToIndexPath == rhsToIndexPath : return true
case (.Updated(let lhsResult, let lhsIndexPath, _), .Updated(let rhsResult, let rhsIndexPath, _)) where lhsResult == rhsResult && lhsIndexPath == rhsIndexPath : return true
default: return false
}
}