ios - 是否允许通过同一个NSManagedContext的performBlock传递NSManagedObject?

标签 ios swift multithreading core-data

我可以在同一 NSManagedContext 的不同执行 block 中设置对象之间的关系吗?

我创建了一个私有(private)上下文 并使用(仅示例):

let pContext = persistentContainer.newBackgroundContext()
pContext.perform {
   let user = pContext.fetch(<fetch Request>).first
   pContext.performAndWait {
        let book = pContext.fetch(<another fetch request>).first
        book.name = "skjkjd"
        pContext.save()
        book.author = user
        pContext.save()
   }
}

这段代码可能会产生以下错误,在什么情况下会产生错误?

Fatal Exception: NSInvalidArgumentException Illegal attempt to establish a relationship 'author' between objects in different contexts

最佳答案

如果我没记错的话,AppDelegate permanentContainer.viewContext 是一个单例。您不应该按照您尝试的方式跨线程传递 MOC。

看一下苹果文档:https://developer.apple.com/documentation/coredata/using_core_data_in_the_background

尝试(未测试):

    let pContext = persistentContainer.newBackgroundContext()
    pContext.perform {
        let user = pContext.fetch(<fetch Request>).first
        let userObjcID = user.objectID
            pContext.performAndWait {
                 let book = pContext.fetch(<another fetch request>).first
                 book.name = "skjkjd"
                 // pContext.save()
                 book.author = pContext.object(with: userObjcID)
        pContext.save()
   }
}

关于ios - 是否允许通过同一个NSManagedContext的performBlock传递NSManagedObject?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58200862/

相关文章:

ios - Swift 3.0 iOS10 通过 Firebase 的 segue 发送器传递异步数据

ios - UITextView,编辑时滚动?

swift - 在 Swift Xcode 中模拟左键单击光标位置

c - Linux C,如何安排10个等待线程以FIFO方式执行?

c# - 在并行线程之间共享kinect流数据

c# - 使用线程对 C# 事件中的循环进行计数

ios - 获取 iOS View 的实际尺寸

ios - 取下耳机时防止视频暂停

iOS 导航后退按钮

ios - 将图像从 Google Places Photo JSON 返回到 imageView