Search code examples
iosswiftfmdb

FMDatabaseQueue is not surviving a class init()


I've been trying to put together the code initializer into the init() function of model class I have like this:

 init?() {
    let docsDir =     NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
    let dbPath = docsDir.stringByAppendingPathComponent("app.sqlite")
    let dbQueue = FMDatabaseQueue(path: dbPath)

    if dbQueue == nil {
        NSLog("%@ : %@", "Problem connecting to the db at", __FUNCTION__)
        return nil
    } else {
        NSLog("%@", "Successfully connected to the db")
    }
}

when I try to use dbQueue from another function of that class it the dbQueue always amount to nil like

 func anotherFunction() {
   dbQueue?.inDatabase{ db in .... }
 }

So when I try to initialize:

 let db = dbConnector()
 db.anotherFunc() // Zilch!

My questions is WHY this is happening and how to fix it. Please help, I'll ask Thor to bless you


Solution

  • I found the solution. I was using let dbQueue on a the class property dbQueue which was actually creating a local variable inside the init() with the same name, leaving the property uninitialized, hence the nil