Crash when saving data to Realm in background thread. | iOS | Swift 4.2

孤人 提交于 2019-12-07 20:47:26

Do like this:

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

General Example:

  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
    }
}

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!