【发布时间】:2012-01-28 01:49:32
【问题描述】:
我的应用程序使用 Core Data(在 Magical Record 的帮助下),并且使用 NSOperation 进行了大量的多线程处理。
当然我非常小心,只在线程/操作之间传递NSManagedObjectID。
现在,为了返回操作中对应的托管对象,我使用-existingObjectWithID:error:,因此:
Collection *owner = (Collection *)[localContext existingObjectWithID:self.containerId error:&error];
但我得到的结果是 nil,error 说这是一个错误 #13300:NSManagedObjectReferentialIntegrityError。
以下是文档中关于此错误的说明:
NSManagedObjectReferentialIntegrityError
Error code to denote an attempt to fire a fault pointing to an object that does not exist.
The store is accessible, but the object corresponding to the fault cannot be found.
在我的情况下这是不正确的:该对象存在。事实上,如果我用NSFetchRequest 遍历该Collection 实体的所有实例,我会在其中找到它,而它的NSManagedObjectID 正是我传递给-existingObjectWithID:error: 的那个。
此外,如果我改用-objectWithID:,我会得到一个正确的对象。
所以我缺少一些东西。以下是一些额外的观察/问题:
- “一个不存在的对象”:那句话中的“存在”是什么意思? “存在”在哪里?那时它肯定“存在”在我的核心数据存储中。
- “找不到故障对应的对象”:那句话中的“找到”是什么意思? “发现”在哪里?那时它肯定会在我的 Core Data 存储中“找到”。
所以也许我错过了existingObjectWithID:error: 的作用?文档说:
If there is a managed object with the given ID already registered in the context, that object is returned directly; otherwise the corresponding object is faulted into the context.
[...]
Unlike objectWithID:, this method never returns a fault.
这对我的问题没有帮助。我不介意让我的对象完全错误,而不是错误。事实上,当我访问对象属性时,其中的任何错误都会在下一行代码中触发。
- 导致
NSManagedObjectReferentialIntegrityError的现实场景是什么?
感谢您的启发。
【问题讨论】:
-
你有没有想过这个问题?我遇到了同样的问题,我的对象肯定在那里并且保存操作正在运行,但它只是偶尔发生。