保存后,ManagedObject的上下文为nil

时间:2013-05-03 16:08:33

标签: ios core-data

这是在后台线程上。它是一个私有并发类型上下文,它在上下文performBlock中执行。我做得对,至少我认为我是。

我不是核心数据的初学者,但是我可能会遗漏一些明显的东西 - 因为我一直盯着这一段时间。

以下是代码:

FFXCollection *backgroundCollection = (FFXCollection *) [context objectWithID:collectionID];

//At this point backgroundCollection.managedObjectContext is the same as context

NSError *error = nil;
[context save:&error];
NSLog(@"error %@", error); //Note that there is no error here

if (!backgroundCollection.managedObjectContext) {
DLog(@"why not?"); //At this point the managedObjectContext is nil!!!
}

为什么managedObjectContext在托管对象中变为nil?

这个例子是人为的,但也证明了我的问题。在我的实际代码中,发生了保存,然后我正在尝试建立关系。然后,当发生另一次保存时,由于上述原因,我得到验证错误。

由于

1 个答案:

答案 0 :(得分:1)

改为使用existingObjectWithID。

  

existingObjectWithID:error:返回指定ID的对象。

     
      
  • (NSManagedObject *)existingObjectWithID:(NSManagedObjectID )objectID错误:(NSError * )error参数objectID请求对象的对象ID。错误如果检索出现问题   objectID指定的对象,返回时包含一个错误   描述了这个问题。返回值objectID指定的对象。   如果对象无法获取,或者不存在,或者不能存在   故障,它返回零。
  •   
     

讨论   如果在上下文中已经注册了具有给定ID的托管对象,则直接返回该对象;否则   相应的对象出现在上下文中。

     

如果未缓存数据,此方法可能会执行I / O.

     

与objectWithID:不同,此方法永远不会返回错误

     

可用性适用于OS X v10.6及更高版本。也可以看看 -   objectWithID: - objectRegisteredForID:声明为   NSManagedObjectContext.h