Skip to content

Instantly share code, notes, and snippets.

Last active May 12, 2018 07:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save groue/2e21172719e634657dfd to your computer and use it in GitHub Desktop.
Save groue/2e21172719e634657dfd to your computer and use it in GitHub Desktop.
Notification of table changes in an SQLite database
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:
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()) {
object: self,
userInfo: [ChangedTableNamesKey: changedTableNames])
func databaseDidRollback(db: Database) {
// Reset until next database event:
changedTableNames = []
// Register observer
let dbQueue = DatabaseQueue()
let observer = TableChangeObserver()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment