在后台线程中将数据保存到Realm时崩溃. | iOS |斯威夫特4.2 [英] Crash when saving data to Realm in background thread. | iOS | Swift 4.2

查看:373
本文介绍了在后台线程中将数据保存到Realm时崩溃. | iOS |斯威夫特4.2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DispatchQueue.global(qos: .background).async {
                    RccContactController.shared.updateDbForAppUsers(contactModels: contacts)
                  }
DispatchQueue.global(qos: .background).async {
                    RccContactController.shared.updateSyncStatus(lastCount : lastIndex)
                    DispatchQueue.main.async {
                        ContactDataStore.shared.updateContacts(withAppUsers: contacts)
                        if let safeDelegate = RccContactController.shared.delegate {
                            safeDelegate.syncedPhonebookContact(contacts: restContacts, appUsers: cont)
                        }
                    }
                }

上面发生了什么事

  • 通过套接字从服务器检索同步的联系人数据
  • 在后台线程中更新数据库中的App用户
  • 在后台线程中更新数据库中的同步状态,并在该过程通过委托通知我的控制器之后.

有时我在第二个线程中崩溃.

Sometimes I'm getting a crash in the second thread.

从com.apple.main.thread(线程1)入队

enqueued from com.apple.main-thread (thread 1)

我在这里怎么了?

推荐答案

执行以下操作:

  DispatchQueue(label: "background").async {
    RccContactController.shared.updateSyncStatus(lastCount : lastIndex)                              
    ContactDataStore.shared.updateContacts(withAppUsers: contacts)
    DispatchQueue.main.async {
        if let safeDelegate = RccContactController.shared.delegate {
            safeDelegate.syncedPhonebookContact(contacts: restContacts, appUsers: cont)
        }
    }
}

常规示例:

  DispatchQueue(label: "background").async {
    do {
        let realm = try Realm(configuration: config)
        let obj = realm.resolve(wrappedObj)

        try realm.write {
            DispatchQueue.main.async {
                //Callback or Update UI in Main thread
            }
        }
    }
    catch {
        //Callback or Update UI in Main thread
    }
}

仅在DispatchQueue.main.async中执行UI操作,其余操作均保留在后台线程中.

Perform only UI Operation in DispatchQueue.main.async rest of keep in a background thread.

这篇关于在后台线程中将数据保存到Realm时崩溃. | iOS |斯威夫特4.2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆