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?
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.
来源:https://stackoverflow.com/questions/55646177/crash-when-saving-data-to-realm-in-background-thread-ios-swift-4-2