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

我创建了一个私人环境
并使用(仅作为示例):

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()
   }
}


此代码可能会产生以下错误,在哪些情况下?


  致命异常:NSInvalidArgumentException
      在不同上下文中非法尝试在对象之间建立关系“作者”

最佳答案

如果我没有记错,但AppDelegatepersistentContainer.viewContext是单例。您不应该按照尝试的方式跨线程传递MOC。

看一下Apple文档: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/

10-12 04:56