 // ============================================================
 
 let dbQueue = DatabaseQueue()
-let defaults = UserDefaults.inDatabase(dbQueue)
-
-defaults.integerForKey("bar") // 0
-defaults.setInteger(12, forKey: "bar")
-defaults.integerForKey("bar") // 12
-
 dbQueue.inDatabase { db in
     let defaults = UserDefaults.inDatabase(db)
+    
+    defaults.integerForKey("bar") // 0
+    defaults.setInteger(12, forKey: "bar")
     defaults.integerForKey("bar") // 12
 }

        return defaults
    }
    
    private init(db: UserDefaultsBackEnd) {
        self.db = db
    }
    

// To run this playground, select and build the GRDBOSX scheme.

import GRDB

/// UserDefaults is a class that behaves like NSUserDefaults.
///
/// Usage:
///
///     let dbQueue = DatabaseQueue(...)
///     dbQueue.inDatabase { db in
///         let defaults = UserDefaults.inDatabase(db)
///         defaults.setInteger(12, forKey: "bar")
///         defaults.integerForKey("bar") // 12
///     }
public class UserDefaults {
    private weak var db: Database!
    private var needsTable: Bool = true
    private static var registeredDefaults: [UserDefaults] = []
    
    /// Returns the defaults for the database
    public static func inDatabase(db: Database) -> UserDefaults {
        registeredDefaults = registeredDefaults.filter { $0.db != nil }
        for defaults in registeredDefaults where defaults.db === db { return defaults }
        let defaults = UserDefaults(db: db)
