首页 > 解决方案 > 如何正确更改合并到子上下文中的父 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 )

谢谢!

标签: iosswiftcore-datansmanagedobjectcontext

解决方案


推荐阅读