我读过其他答案,但找不到合适的解决办法。
我有一个产品是上传到服务器,只有当所有图片属于该产品已经完成上传。产品的详细信息(连同图像)填写在视图控制器1上,然后他被带到下一个屏幕(视图控制器2),无论是否所有图像都已完成上载。我的VC1完成了这样的产品上传过程。

let areAllImagesUploaded = RetailProductsService.sharedInstance.checkProductImageDependency(realm!, uuid: retailProduct.getClientId())

if areAllImagesUploaded {
    uploadProductToServer(retailProduct)
} else {
    do {
        try realm = Realm()
        RetailProductsService.sharedInstance.updateSyncStatusForSellerProduct(realm!, clientId: retailProduct.getClientId(), syncStatus: ProductSyncStatus.SYNC_FAILED)
        let groupT = dispatch_group_create()

        for sellerSKU in retailProduct.sellersSKUs {
            for productImage in sellerSKU.productImages {
                dispatch_group_enter(groupT)
                let imageUploadInfo = ImageUploadInfo(productId: retailProduct.getClientId(), imageId: sellerSKU.getId(),imageData: productImage.imageData, uploadURL: ServerConfig.RETAIL_SERVER_UPLOAD_FILE_URL)
                ImageUploadManager.sharedInstance.queueImageForUpload(imageUploadInfo, completion: { (success, error) -> Void in
                    dispatch_group_leave(groupT)
                })

                dispatch_group_notify(groupT, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
                    //self.uploadProduct(retailProduct)
                    self.uploadProductToServer(retailProduct) // Fails here
                })

            }
        }
    } catch {
        print("Error in saving product.")
    }
}

我已经标出了我犯这个错误的那条线。我的应用程序已移动到下一个视图控制器,而视图控制器1中的此功能继续上载图像,并且一旦与产品关联的所有图像上载到服务器,它将尝试上载产品。但是它失败了,只有这个例外。
Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread'

请帮忙!

最佳答案

无法从不同线程访问领域对象。您的retailProduct由threadX创建或从领域存储中获取,而不是通过调用dispatch_group_notify切换到其他线程(threadY)。要修复异常,可能需要执行以下操作:
我假设您的retailProduct对象属于RetailProduct类型,并且有一个id属性用作领域存储中的主键。当然,您可以使用其他查询来获取retailProduct

let retailProductId = retailProduct.id
dispatch_group_notify(groupT, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
       // threadY executing this lines
       if let retailProduct = realm.objectForPrimaryKey(RetailProduct.self, key: retailProductId){
          self.uploadProductToServer(retailProduct)
       }
 })

关于swift - dispatch_group_notify块引发“从错误的线程访问 Realm ”异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34259379/

10-10 02:34