NSManagedObject内存关联值异常:Core Data多上下文冲突疑问
Core Data 多上下文冲突与行缓存行为疑问
示例代码
为何该测试能成功?
场景描述
存在3个同一协调器下的上下文,意味着它们共享行缓存(row cache)。
- 在
context1中向数据库插入以下数据:
/// EntityA(attribute: 100).toManyRelationship = [EntityB(attribute: 10), EntityB(attribute: 11)] /// EntityA(attribute: 200).toManyRelationship = [EntityB(attribute: 11), EntityB(attribute: 12)] /// /// EntityB(attribute: 10).toManyRelationship = [EntityA(attribute: 100)] /// EntityB(attribute: 11).toManyRelationship = [EntityA(attribute: 100), EntityA(attribute: 200)] /// EntityB(attribute: 12).toManyRelationship = [EntityA(attribute: 200)]
- 将
context1的mergePolicy设置为**.overwrite**。 - 在
context1中从EntityA(attribute: 100)删除EntityB(attribute: 10),不保存。 - 在
context2中从EntityA(attribute: 100)删除EntityB(attribute: 11),保存更改。 - 保存
context1的更改,此时会发生冲突。 - Core Data已解决冲突,当前数据库存储的数据如下:
/// EntityA(attribute: 100).toManyRelationship = [] /// EntityA(attribute: 200).toManyRelationship = [EntityB(attribute: 11), EntityB(attribute: 12)] /// /// EntityB(attribute: 10).toManyRelationship = [] /// EntityB(attribute: 11).toManyRelationship = [EntityA(attribute: 200)] /// EntityB(attribute: 12).toManyRelationship = [EntityA(attribute: 200)]
- 但如果在
context3中用新创建的获取请求获取数据,结果为:
/// EntityA(attribute: 100).toManyRelationship = [EntityB(attribute: 10)] ?????? /// ...其余数据与上述一致
疑问探讨
- 我认为关联数据是从行缓存而非SQLite存储获取的,但为何
EntityA(attribute: 100).toManyRelationship不为空? - 另外,若在
context4这类不同上下文或其他协调器下的上下文插入数据,执行步骤2~6后结果会与SQLite存储一致(这是我预期的结果)。
请问各位对此有何见解?感谢解答!
内容的提问来源于stack exchange,提问作者Ckitakishi
相关产品推荐
相关产品推荐

