Core Data -existingObjectWithID:error:导致错误133000

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:,我会得到一个正确的对象.

所以我有些东西不见了.以下是一些其他观察/问题:

  • "一个不存在的对象":那句话中"存在"的含义是什么?"存在"在哪里?那时它在我的Core Data商店中肯定"存在".
  • "无法找到与故障对应的对象":该句中"找到"的含义是什么?"发现"在哪里?在那时我肯定会在我的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.
Run Code Online (Sandbox Code Playgroud)

这对我的问题没有帮助.我不介意让我的物体完全出错,而不是故障.实际上,当我访问对象属性时,其中的任何错误都将在下一个代码行上触发.

  • 什么是一个现实的场景导致NSManagedObjectReferentialIntegrityError

感谢任何启示.

Ale*_*kov 39

问题是NSManagedObjectID你传球是暂时的.你可以通过调用检查它NSManagedObjectIDisTemporaryID方法.来自docs:

返回一个布尔值,指示接收器是否是临时的.

大多数对象ID返回NO.插入到托管对象上下文中的新对象将分配一个临时ID,一旦将对象保存到持久性存储,该ID将替换为永久ID.

您应该首先将更改保存到持久存储,然后才能获取永久ID以传递给其他上下文.


Dan*_*ert 8

当您使用多个上下文时,需要确保在将托管对象ID从上下文A传递到另一个上下文B之前保存上下文A.只有在保存完成后才能从上下文B访问该对象.

-objectWithID:将始终返回一个非nil对象,但如果在商店中没有后备对象,它将在您开始使用它时抛出异常.-existingObjectWithID:error:实际上会运行一些SQL并执行I/O,如果该对象尚未在其使用的上下文中注册.

  • 你对"在managedObjectContext上进行重置"是什么意思? (7认同)
  • 那不是它:当我使用`-objectWithID:`时,我得到了正确的对象(就像我写的那样):我可以使用它,访问它的属性,它的关系,一切.事实上,之前创建它的环境得到了保存.然而,`-existingObjectWithID:error:`仍然失败,错误133000. (3认同)