You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 23:50:36