代码之家  ›  专栏  ›  技术社区  ›  Dania

使用背景上下文时,无法在不同上下文中的对象之间建立关系

  •  0
  • Dania  · 技术社区  · 6 年前

    我想插入一个 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 ()
                    }
                }
    
    
        }
    

    我只有两个实体,位置和图像。位置有一个称为位置的属性,图像有一个称为图像的属性。它们之间有一对多的关系(一个位置可以有多个图像)。

    我知道,每个上下文都保留自己的 NSManagedObjects . 这就是为什么在代码中,我首先得到一个基于视图上下文的图像,得到它的ID,然后使用该ID在背景上下文中得到一个图像对象。

    我做错什么了?

    我对核心数据不熟悉,所以我会感谢任何能解释我这里发生了什么以及我如何解决它的帮助。

    更新 :问题出在 imagesLocation 它是基于视图上下文构建的,所以我只是使用它在后台上下文中的ID从中创建了一个对应的对象。在那之后,问题解决了,但我也有一个像我的问题一样的图像对象和关系的问题。 here . 我可以解决这个问题,我发布了答案,你可以检查一下。

    1 回复  |  直到 6 年前
        1
  •  1
  •   FJ de Brienne    6 年前

    好像 self.imagesLocation 是在外部线程上创建的nsmanagedObject,因此不能分配给 imageOnBackgroundContext .

    你应该把 自拍图像位置 在你 backgroundContext 利用其 NSManagedObjectID 并将获取的对象分配给 图片背景上下文