ios - 如何正确更改合并到子上下文中的父 NSManagedObjectContext?
问题描述
我有一个关于处理 parent 和 child 的问题NSManagedObjectContexts
。
我使主要上下文(XCode 在项目中自动设置的那个CoreData
)可以像这样访问:App.managedObjectContext
比如说,我创建了一个子项context
,用于显示和编辑一些数据的详细视图,例如:
let context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
context.parent = App.managedObjectContext
context.automaticallyMergesChangesFromParent = true
let detailVC = DetailVC(context: context)
// present(...)
比方说,detailVC
你想在全局范围内进行更改(因此App.managedObjectContext
更改并将更改合并到创建的子上下文中)
我可以简单地这样做:
// Example: App.managedObjectContext.delete(/*some object*/)
try? App.managedObjectContext.save()
这有效,并且更改被合并到子上下文中。但这会在主队列上执行保存。我不应该总是在后台队列中更改内容吗?我通常的做法是:
// Get the persistent container whose `viewContext` is App.managedObjectContext
App.appDelegate.persistentContainer.performBackgroundTask { (privateContext) in
// Do changes
}
但是,这些更改并未合并到子上下文中。我该怎么做?我的想法是这样的:
let newChild = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
newChild.parent = context.parent
// As I understand it, perform() will run on a background queue in this case, right?
newChild.perform {
// Example modification:
// let object = newChild.object(with: civilization.objectID)
// newChild.delete(object)
try? newChild.save()
newChild.parent?.perform {
try? newChild.parent?.save()
}
}
这似乎有效,但这有任何副作用或缺点吗?它实际上是在后台队列上运行的吗?
(我已经阅读了这篇文章NSManagedObjectContext
并学到了一些东西,但这对我来说仍然不清楚:https ://developer.apple.com/documentation/coredata/nsmanagedobjectcontext )
谢谢!
解决方案
推荐阅读
- laravel - Laravel 急切加载特定列错误
- prestashop-1.7 - 客户注册时将 GET-Var 存储在 Prestashop 中
- c# - 在不使用外部工具的情况下分析 C# 应用程序
- machine-learning - 使用统计模型进行特征选择
- laravel - 在 vuejs 中保存输入的初始值
- nuxt.js - 修改 .nuxt 文件夹的权限被拒绝
- c++ - 使用类型类的向量时获取“未声明的标识符”
- c - 我需要在 c 中使用 getopt 将目录作为命令行参数
- wordpress - 在 wordpress 中显示 id 12 到 25 之间的帖子
- python - Python timeit 模块导致无限循环