ios - 使用后台上下文时无法在不同上下文中的对象之间建立关系
问题描述
我试图NSManagedObject
通过背景上下文插入一个,我收到了这个错误:
Illegal attempt to establish a relationship 'location' between objects in different contexts (source = <Image: 0x600002f81b80> (entity: Image; id: 0x600000f44fe0 <x-coredata:///Image/t8C3934D6-DCD7-4A7B-A69C-9C18334F7A942> ; data: {
image = <ffd8ffe0 00104a46 49460001 01000048 00480000 ffe10058 45786966 00004d4d 002a0000 00080002 01120003 00000001 0001>;
location = nil;
}) , destination = <Location: 0x600002fb3020> (entity: Location; id: 0xd78dad45136e9365 <x-coredata://9CA497CF-69A8-44ED-8741-C75AF480446E/Location/p2> ; data: {
images = "<relationship fault: 0x600000f44480 'images'>";
location = "29.977646364835238,31.32489065578125";
}))
我知道这个问题之前被问过好几次,我已经检查了一些答案,但我真的不知道我的代码缺少什么。这是我的代码:
func saveImagesToDb () {
//Store the image in the DB along with its location on the background thread
dataController.backgroundContext.perform {
let imageOnMainContext = Image (context: self.dataController.viewContext)
let imageManagedObjectId = imageOnMainContext.objectID
let imageOnBackgroundContext = self.dataController.backgroundContext.object(with: imageManagedObjectId) as! Image
for downloadedImage in self.downloadedImages {
let imageData = NSData (data: downloadedImage.jpegData(compressionQuality: 0.5)!)
imageOnBackgroundContext.image = imageData as Data
imageOnBackgroundContext.location = self.imagesLocation
try? self.dataController.backgroundContext.save ()
}
}
}
我只有两个实体,位置和图像。Location 有一个名为 location 的属性,Image 有一个名为 image 的属性。它们之间存在一对多的关系(一个位置可以有许多图像)。
我知道每个上下文都保留自己的NSManagedObjects
. 这就是为什么在代码中我首先根据视图上下文得到一个 Image,得到它的 id,然后使用该 id 在背景上下文中获取一个 Image 对象。
我究竟做错了什么?
我是 Core Data 的新手,所以我将不胜感激任何可以向我解释这里发生了什么以及如何解决它的帮助。
更新:问题在于imagesLocation
它是建立在视图上下文上的,所以我只是使用它在背景上下文中的 ID 从它创建了一个相应的对象。之后,问题就解决了,但我也遇到了 Image 对象和关系的问题,就像我的问题一样。我可以解决这个问题,我发布了答案,你可以检查一下。
解决方案
似乎self.imagesLocation
是在外部线程上创建的 NSManagedObject ,因此不能分配给imageOnBackgroundContext
.
您应该self.imagesLocation
在backgroundContext
使用它时获取指向的对象NSManagedObjectID
并将该获取的对象分配给您的imageOnBackgroundContext
推荐阅读
- python - 天真的分类器使用 dict 的键来遍历 df 的列?
- php - 在下面的查询中添加 Custom Guard admin 以获取 Admin ID 值
- javascript - 如何从 Javascript/Google App 脚本中的另一个函数调用数组
- node.js - 如何在 Mongoose 的数组中添加数据?
- regex - 在apache spark中使用rlike时是否可以知道执行了哪个正则表达式
- python - 我们可以使用 Python 录制视频群聊会议电话吗?
- sprite-kit - SpriteKit 节点淡入问题
- excel - 编译错误:过程太大(VBA 错误)
- c# - 通过中间件来自不同服务器的令牌身份验证(身份服务器 4),但它检查所有不需要授权的端点
- node.js - 在 Windows 上使用 pm2 时如何传递节点参数