我试图通过后台上下文插入一个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和Image。location有一个名为Location的属性,image有一个名为Image的属性。它们之间是一对多的关系(一个位置可以有多个图像)。
我知道每个上下文都保留了自己的NSManagedObjects
副本。这就是为什么,在代码中,我首先根据视图上下文获取一个Image,获取其id,然后使用该id获取背景上下文中的Image对象。
我做错了什么?
我刚接触Core Data,所以我非常感谢任何可以向我解释这里发生了什么以及我如何解决它的帮助。
更新:问题出在构建在视图上下文上的imagesLocation
,所以我只是在它的背景上下文中使用它的ID创建了一个相应的对象。在那之后,问题解决了,但我也遇到了图像对象和关系的问题,就像在我的问题here中一样。我可以解决这个问题,我发布了答案,你可以查看它。
发布于 2018-12-31 23:19:30
看起来好像self.imagesLocation
是在外部线程上创建的NSManagedObject,因此不能分配给imageOnBackgroundContext
。
您应该在backgroundContext
中使用其NSManagedObjectID
获取self.imagesLocation
指向的对象,并将获取的对象分配给您的imageOnBackgroundContext
https://stackoverflow.com/questions/53987377
复制相似问题