一旦从另一个线程获得结果,如何更新领域对象?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一旦从另一个线程获得结果,如何更新领域对象?相关的知识,希望对你有一定的参考价值。
如何更新领域对象t#1。
问题是requestAuthorization调用需要依赖于结果,这会产生一个单独的线程。
使用DispatchQueue.main.async没有帮助。
@IBAction func notificationToggle(_ sender: UISwitch) {
if (sender.isOn){
//Notifications being turned on
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
print("Permission granted: \(granted)")
if granted{
myRealmObject.generateNotificationItems() //#1. Throws error due to not being in the main thread
}
else{
self.showNotificationsPrompt()
}
}
}
else{
myRealmObject.deleteNotificationItems() //#2. This is fine, being in the main thread.
}
}
答案
您可以使用ThreadSafeReference
跨线程传递Realm对象,如下所述:https://realm.io/docs/swift/latest/#passing-instances-across-threads
@IBAction func notificationToggle(_ sender: UISwitch) {
if (sender.isOn){
//Notifications being turned on
let objectRef = ThreadSafeReference(to: myRealmObject)
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
(granted, error) in
autoreleasepool {
print("Permission granted: \(granted)")
if granted{
let realm = try! Realm()
guard let obj = realm.resolve(objectRef) else { return }
obj.generateNotificationItems()
}
else{
self.showNotificationsPrompt()
}
}
}
}
else{
myRealmObject.deleteNotificationItems() //#2. This is fine, being in the main thread.
}
}
以上是关于一旦从另一个线程获得结果,如何更新领域对象?的主要内容,如果未能解决你的问题,请参考以下文章