首页 > 解决方案 > 使用后台上下文时无法在不同上下文中的对象之间建立关系

问题描述

我试图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 对象和关系的问题,就像我的问题一样。我可以解决这个问题,我发布了答案,你可以检查一下。

标签: iosswiftxcodecore-data

解决方案


似乎self.imagesLocation是在外部线程上创建的 NSManagedObject ,因此不能分配给imageOnBackgroundContext.

您应该self.imagesLocationbackgroundContext使用它时获取指向的对象NSManagedObjectID并将该获取的对象分配给您的imageOnBackgroundContext


推荐阅读