FMDatabaseQueue 没有在类 init() 中幸存

Posted

技术标签:

【中文标题】FMDatabaseQueue 没有在类 init() 中幸存【英文标题】:FMDatabaseQueue is not surviving a class init() 【发布时间】:2015-02-13 22:07:53 【问题描述】:

我一直在尝试将代码初始化程序放在模型类的init() 函数中,我有这样的:

 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")
    

当我尝试从该类的另一个函数中使用 dbQueue 时,dbQueue 总是等于 nil 之类的

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

所以当我尝试初始化时:

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

我的问题是为什么会发生这种情况以及如何解决它。请帮忙,我会请托尔祝福你

【问题讨论】:

【参考方案1】:

我找到了解决方案。我在类属性dbQueue 上使用let dbQueue,它实际上是在init() 内创建一个同名的局部变量,使属性未初始化,因此nil

【讨论】:

以上是关于FMDatabaseQueue 没有在类 init() 中幸存的主要内容,如果未能解决你的问题,请参考以下文章

FMDatabaseQueue 如何返回一个值

FMDatabaseQueue 被称为可重入错误

_fmdatabaseQueue 可以从其他类访问吗

在类 __init__() 中获取实例名称

执行 [FMDatabaseQueue inDatabase:] 后出现错误,因为周围至少有一个打开的结果集?

在类路径资源中定义名称为“entityManagerFactory”的 bean 创建错误:调用 init 方法失败