ios - 是否允许通过相同 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 非法尝试在不同上下文中的对象之间建立关系“作者”
解决方案
如果我没记错的话,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()
}
}
推荐阅读
- javascript - 用 CKEditor 5 锁定段落
- javascript - React 功能组件的功能或粗箭头?
- r - 在 RStudio 中的 mac 上创建 zip 包
- azure - 在 Azure 中验证应用服务证书时出现问题
- tortoisesvn - Tortoise SVN 撤消存储库中的签出
- groovy - Groovy 脚本 - 比较 SOAPUI 项目属性
- java - 当我尝试打开应用程序时,它显示“不幸的是应用程序停止”即崩溃。那么,如何解决这个问题?
- javascript - 未处理的拒绝(TypeError):无效的解构不可迭代实例的尝试
- ios - Slack 斜杠命令导致来自 iOS 应用程序或 MacOS 应用程序的不同编码
- php - PDFTK 无法创建用户目录