Search code examples
iosswiftmultithreadingthread-safetyrealm

Realm accessed from incorrect thread Swift


im using Realm to save the data retrieved from QRCode as below:

self.barcodesHandler = { barcodes in
    if !self.dispatched {
        self.dispatched = true
        for barcode in barcodes {
            print("Barcode found: type=" + barcode.type + " value=" + barcode.stringValue)
            let barcodeStringArray  = barcode.stringValue.components(separatedBy: ": ")
            let infoVC = ANSProductDetailViewController()
            self.product = ANSProductModel(name: barcodeStringArray[1], manufacturer: barcodeStringArray[2], registerLocation: barcodeStringArray[0], detailUrl: barcodeStringArray[3])
            infoVC.product = self.product
            DispatchQueue.main.async(execute: {
                infoVC.hidesBottomBarWhenPushed = true
                self.navigationController?.pushViewController(infoVC, animated: true)
            })
            break
        }
        self.product.saveToLocal()
    }
}

 //ANSProductModel save method, self = ANSProductModel
  func saveToLocal() {
    Realm.execute { (realm) in
    realm.add(self, update: true)
    print("Product saved")
 }
}

However, after print the log, it threw an exception called "Realm accessed from incorrect thread Swift". I've read some similar question, but still not understand clearly, so please anyone can help me clarify this issues, and how should i fix in my code. Thanks so much


Solution

  • I'm not familiar with Realm but it appears that you may have to call it from the main thread? Try printing out the current thread in your log (Thread.current) to see if your on a background one.

    If thats the case wrap your execute/add calls in DispatchQueue.main.async(execute: {}) to see if that fixes the issue?