应用程序因 FMDB 查询更新 ios 而冻结

Posted

技术标签:

【中文标题】应用程序因 FMDB 查询更新 ios 而冻结【英文标题】:app freezes with FMDB query update ios 【发布时间】:2018-01-24 22:41:58 【问题描述】:

当我更新数据库中的值时,我的应用程序冻结。这是我用来检查服务器中是否有任何值更改的代码。

 DataService.ds.REF_POSTS.observe(.childChanged, with:  (snapshot) in

        let postDict = snapshot.value as? Dictionary<String, AnyObject>
        self.db.updateBook(bookName: postDict!["book_name"] as! String, id: postDict!["id"] as! String)
        self.arrayBooks.removeAll()
        self.arrayBooks.append(contentsOf: self.db.fetchAll())
        self.collectionView.reloadData()
    )

这是具有updateBook函数的数据库类

  func updateBook (bookName : String , id: String) 
        let sqlString = "UPDATE magazine SET book_name='\(bookName)' WHERE id='\(id)'"
        if self.fmdb.executeUpdate(sqlString, withArgumentsIn: [])             
        
    

当应用程序冻结时,我在 xcode 中按下暂停键,看看我遇到了什么错误。 错误是:

[FMDatabase executeUpdate:error:withArgumentsInArray:orVAList:]

[FMDatabase executeUpdate:withArgumentsInArray:]

updateBook(bookName:id:)

closure #2 in controller.viewDidLoad()

【问题讨论】:

我不认为这些是错误;我怀疑这是直到您单击暂停按钮为止的堆栈跟踪。应用程序“冻结”的原因是您正在主线程上执行“长时间运行的进程”。无论出于何种原因,您的 SQL 运行时间过长……数据库行数、索引、触发器等等……某些事情花费的时间太长。 我没有使用 FMDB,但基于签名...我想知道您是否应该对“sqlString”中的变量使用转义字符并传递该参数数组中的值。也许这就是造成问题的原因?就像,也许那个数组不应该是空的。 【参考方案1】:

我通过更改数据库类中的更新函数解决了这个问题

 func updateBook (bookName : String , id: String) 

        DispatchQueue.main.async 


        let sqlString = "UPDATE magazine SET book_name='\(bookName)' WHERE id='\(id)'"

        if self.fmdb.executeUpdate(sqlString, withArgumentsIn: [bookName,id]) 

            print("sql string  \(sqlString)")
        
             

    

所以基本上更新会在主线程DispatchQueue.main.async

【讨论】:

以上是关于应用程序因 FMDB 查询更新 ios 而冻结的主要内容,如果未能解决你的问题,请参考以下文章

iOS sqlite/FMDB 更新不起作用

如何在我的 iOS 应用程序中调试冻结问题

iOS FMDB 无法更新二进制数据的问题

iOS 应用程序在解析异步查询期间冻结

WKWebView 因某些查询而崩溃(iOS Swift)

iOS 14 更新后应用程序在文本字段上冻结