Last active
May 12, 2018 07:43
-
-
Save groue/2e21172719e634657dfd to your computer and use it in GitHub Desktop.
Notification of table changes in an SQLite database http://github.com/groue/GRDB.swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import GRDB | |
/// The notification posted when database tables have changed: | |
let DatabaseTablesDidChangeNotification = "DatabaseTablesDidChangeNotification" | |
let ChangedTableNamesKey = "ChangedTableNames" | |
/// TableChangeObserver posts a DatabaseTablesDidChangeNotification on the main | |
/// thread after database tables have changed. | |
class TableChangeObserver : NSObject, TransactionObserverType { | |
private var changedTableNames: Set<String> = [] | |
func databaseDidChangeWithEvent(event: DatabaseEvent) { | |
// Remember the name of the changed table: | |
changedTableNames.insert(event.tableName) | |
} | |
func databaseWillCommit() throws { | |
// Let go | |
} | |
func databaseDidCommit(db: Database) { | |
// Extract the names of changed tables, and reset until next | |
// database event: | |
let changedTableNames = self.changedTableNames | |
self.changedTableNames = [] | |
// Notify | |
dispatch_async(dispatch_get_main_queue()) { | |
NSNotificationCenter.defaultCenter().postNotificationName( | |
DatabaseTablesDidChangeNotification, | |
object: self, | |
userInfo: [ChangedTableNamesKey: changedTableNames]) | |
} | |
} | |
func databaseDidRollback(db: Database) { | |
// Reset until next database event: | |
changedTableNames = [] | |
} | |
} | |
// Register observer | |
let dbQueue = DatabaseQueue() | |
let observer = TableChangeObserver() | |
dbQueue.addTransactionObserver(observer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment