【问题标题】:How to update a realm object once a result has been obtained from another thread?从另一个线程获得结果后如何更新领域对象?
【发布时间】:2018-03-06 11:57:10
【问题描述】:

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

【问题讨论】:

    标签: swift multithreading realm


    【解决方案1】:

    您可以使用 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.
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多