我已阅读其他答案,但找不到合适的解决方案。
我有一个产品,只有当属于该产品的所有图像都已完成上传时才会上传到服务器。产品的详细信息(连同图像)填充在 View Controller 1 上,然后他被带到下一个屏幕( View Controller 2),无论所有图像是否已完成上传。 MY 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.")
}
}
我已经标记了出现此错误的行。我的应用程序已移至下一个 View Controller ,而 View Controller 1 中的此功能继续上传图像,一旦与产品相关的所有图像都上传到服务器,它就会尝试上传产品。然而,它因这个异常而失败。
Terminating app due to uncaught exception 'RLMException', reason: 'Realm accessed from incorrect thread'
请帮忙!
最佳答案
Realm 对象不能从不同的线程访问。您的 retailProduct
由 threadX 创建或从 Realm 存储中获取,而不是您通过调用 dispatch_group_notify
切换到其他线程 (threadY)。要修复异常,您可能需要执行以下操作:
我假设您的 retailProduct
对象属于 RetailProduct 类型,并且有一个 id 属性用作 Realm 存储中的主键。当然,您可以使用另一个查询来获取 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 block 抛出的 "Realm accessed from incorrect thread"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34259379/