Crash when saving data to Realm in background thre

2019-08-23 07:48发布

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

What's happening above:

  • retrieving the synced contacts data from the server via Socket
  • Update App users in DB in a background thread
  • Update sync status in DB in a background thread and after the process notifies my controller through a delegate.

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

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

What's wrong am I doing here?

1条回答
家丑人穷心不美
2楼-- · 2019-08-23 08:38

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.

查看更多
登录 后发表回答