// 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"
}
我不明白为什么从父上下文的更改会自动到达子上下文。请解释为什么会发生这种情况。
您以前从未获得过钱包,因此子上下文正在联系其父上下文以查找对象。它不会自动合并更改,它只是按照文档中的说明进行操作:
如果对象未在上下文中注册,则它可能会被提取或作为错误返回。
如果在父上下文中创建钱包,从子上下文中获取对它的引用,然后在父上下文中更改它,您将看到子对象没有更改。根据定义,未注册的对象必须来自父上下文或持久存储,否则您将创建同一对象的多个版本。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句