首页 > 解决方案 > 是否允许通过相同 NSManagedContext 的 performBlock 传递 NSManagedObject?

问题描述

我可以设置不同对象之间的关系执行相同的 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 非法尝试在不同上下文中的对象之间建立关系“作者”

标签: iosswiftmultithreadingcore-data

解决方案


如果我没记错的话,AppDelegate persistentContainer.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()
   }
}

推荐阅读