swift - 为什么父上下文的更改会自动转到子上下文?
问题描述
// 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"
}
我不明白为什么父上下文的更改会自动到达子上下文。请解释为什么会这样。
解决方案
您以前从未获得过钱包,因此子上下文正在到达其父上下文以查找对象。它不会自动合并更改,它只是按照文档中的说明进行操作:
如果对象没有在上下文中注册,它可能会被获取或作为错误返回。
如果你在父上下文中创建钱包,从子上下文中获取对它的引用,然后在父上下文中更改它,你会看到子对象没有改变。根据定义,未注册的对象必须来自父上下文或持久存储,否则您将创建同一对象的多个版本。
推荐阅读
- android - 带有谷歌包的奇怪 NullPointerException WebSocketHandshake.verifyServerHandshakeHeaders
- office365 - 尝试使用未经许可的用户进行模拟时出现 Office 365 问题
- iframe - 带有 webplayer 的 iframe:未捕获的 ReferenceError:未定义 BrowserDetect
- vivado-hls - Vivado HLS RTL/协同仿真失败
- ios - 配置文件中的重复键导致构建失败:错误 MSB4018
- c# - 如何正确使用 Unity Transport API?
- react-native - 如何在 react-native-router-flux 中使用 react-navigation 中的 onNavigationStateChange?
- javascript - 将值复制到剪贴板
- javascript - 在javascript中对一个子数组进行排序时如何更改多维数组中的顺序?
- java - 如何在一个组件中创建实例,但在另一个组件中使用?