Jea*_*uys 40 cocoa core-data fault
我的应用程序使用核心数据(在Magical Record的帮助下)并使用相当多的多线程NSOperation.
当然,我非常小心,只能NSManagedObjectID在线程/操作之间传递.
现在,为了回到操作中相应的托管对象,我使用-existingObjectWithID:error::
Collection *owner = (Collection *)[localContext existingObjectWithID:self.containerId error:&error];
Run Code Online (Sandbox Code Playgroud)
但我得到的是零,并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.
Run Code Online (Sandbox Code Playgroud)
在我的情况下,这不是真的:该对象存在.实际上,如果我用a迭代遍历该Collection实体的所有实例NSFetchRequest,我会在其中找到它,它NSManagedObjectID就是我传递给它的那个实体-existingObjectWithID:error:.
而且,如果我使用-objectWithID:,我会得到一个正确的对象.
所以我有些东西不见了.以下是一些其他观察/问题:
所以也许我错过了什么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.
Run Code Online (Sandbox Code Playgroud)
这对我的问题没有帮助.我不介意让我的物体完全出错,而不是故障.实际上,当我访问对象属性时,其中的任何错误都将在下一个代码行上触发.
NSManagedObjectReferentialIntegrityError?感谢任何启示.
Ale*_*kov 39
问题是NSManagedObjectID你传球是暂时的.你可以通过调用检查它NSManagedObjectID的isTemporaryID方法.来自docs:
返回一个布尔值,指示接收器是否是临时的.
大多数对象ID返回NO.插入到托管对象上下文中的新对象将分配一个临时ID,一旦将对象保存到持久性存储,该ID将替换为永久ID.
您应该首先将更改保存到持久存储,然后才能获取永久ID以传递给其他上下文.
当您使用多个上下文时,需要确保在将托管对象ID从上下文A传递到另一个上下文B之前保存上下文A.只有在保存完成后才能从上下文B访问该对象.
-objectWithID:将始终返回一个非nil对象,但如果在商店中没有后备对象,它将在您开始使用它时抛出异常.-existingObjectWithID:error:实际上会运行一些SQL并执行I/O,如果该对象尚未在其使用的上下文中注册.