Swift:从错误的线程访问的域

时间:2016-07-11 07:44:42

标签: ios swift realm

我从之前的视图控制器传递它。我想要显示我保存在其他视图控制器中的数据。

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if (segue.identifier == "Beacons") {


        let nav = segue.destinationViewController as! UINavigationController
        let svc = nav.topViewController as! BeaconCharacteristicViewController
        svc.selectedList = sender as! Beacons


    }

      var selectedList : Beacons!

这段代码出于某种原因出错。

我没有使用主键,或者我必须使用它。

    func loadproperties(){

      let beacons = selectedList

      let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT

      dispatch_async(dispatch_get_global_queue(priority, 0)) {

        do{
            try uiRealm.write({ () -> Void in

                beacons.uuid = self.beaconUUID.text!
                print("uuid = \(beacons.uuid)")

                beacons.major = self.beaconMajor.text!
                print("uuid = \(beacons.uuid)")

                beacons.minor = self.beaonMinor.text!
                print("uuid = \(beacons.uuid)")

                uiRealm.add(beacons, update: true)

                }
            )
        } catch {
            print("error")
        }

       }
    }

错误

       Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread.'

谢谢:))))

1 个答案:

答案 0 :(得分:2)

根据您的代码try uiRealm.write,您似乎在主线程(调度块)中调用另一个线程的realm实例。尝试创建另一个实例。

    do{
        // create new instance
        let uiRealm = try! Realm()

        try uiRealm.write({ () -> Void in

            beacons.uuid = self.beaconUUID.text!
            print("uuid = \(beacons.uuid)")

            beacons.major = self.beaconMajor.text!
            print("uuid = \(beacons.uuid)")

            beacons.minor = self.beaonMinor.text!
            print("uuid = \(beacons.uuid)")

            uiRealm.add(beacons, update: true)

            }
        )
    } catch {
        print("error")
    }