gpt4 book ai didi

swift - 从另一个线程获得结果后如何更新 Realm 对象?

转载 作者:行者123 更新时间:2023-11-30 11:42:59 25 4
gpt4 key购买 nike

如何更新 Realm 对象 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.
}
}

关于swift - 从另一个线程获得结果后如何更新 Realm 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49130283/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com