Swift 为什么父上下文的更改会自动转到子上下文?

Swift 为什么父上下文的更改会自动转到子上下文?,swift,core-data,Swift,Core Data,我不明白为什么父上下文的更改会自动进入子上下文。请解释发生这种情况的原因。您以前从未获得过钱包,因此子上下文正在向其父上下文传递以查找该对象。它不是自动合并更改,只是按照文档中的说明执行: 如果对象未在上下文中注册,则可能会将其作为错误获取或返回 如果在父上下文中创建钱包,从子上下文中获取对钱包的引用,然后在父上下文中更改钱包,则会看到子对象没有更改。根据定义,未注册的对象必须来自父上下文或持久存储,否则将创建同一对象的多个版本 // Getting the main context: let

我不明白为什么父上下文的更改会自动进入子上下文。请解释发生这种情况的原因。

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

如果对象未在上下文中注册,则可能会将其作为错误获取或返回

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

// 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"
}