首页 > 解决方案 > 为什么父上下文的更改会自动转到子上下文?

问题描述

// Getting the main context:
let mainContext = appDelegate.persistentContainer.viewContext

// Creating a child context:
let childContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
childContext.parent = mainContext
print(childContext.automaticallyMergesChangesFromParent) // false

// Creating an object after creating a child context and setting its value
let wallet = WalletMO.init(context: mainContext)
wallet.currencyCode = "USD"

// Trying to get an object from a child context. And we get it successfully. Why?
if let walletFromChildContext = childContext.object(with: wallet.objectID) as? WalletMO {
   print(walletFromChildContext.currencyCode ?? "nil") // "USD"
}

我不明白为什么父上下文的更改会自动到达子上下文。请解释为什么会这样。

标签: swiftcore-data

解决方案


您以前从未获得过钱包,因此子上下文正在到达其父上下文以查找对象。它不会自动合并更改,它只是按照文档中的说明进行操作:

如果对象没有在上下文中注册,它可能会被获取或作为错误返回。

如果你在父上下文中创建钱包,从子上下文中获取对它的引用,然后在父上下文中更改它,你会看到子对象没有改变。根据定义,未注册的对象必须来自父上下文或持久存储,否则您将创建同一对象的多个版本。


推荐阅读