2013-10-06 28 views
0

我使用两个上下文,以便如果用户创建我的NSManagedObjectModel子类,AddressAnnotation(点在地图上),当用户创建一个新的路由时(我的另一个实体,与AddressAnnotation的多种关系),那么如果他们决定取消,我可以很容易地丢弃这些对象,因为它们是在tempContext中创建的。这样的代码如下所示:编辑以前保存的实体时使用两个ManagedObjectContexts

 AddressAnnotation *anAddress = [AddressAnnotation insertAddressAnnotationWithCoordinate:coordinate inManagedObjectContext:self.tempContext]; 
     [self.route addAddressAnnotationsObject:anAddress]; 

然后,当我保存地址和路由,我这样做:

NSManagedObjectContext *tempContext = [self.route managedObjectContext]; 

    [tempContext performBlock:^{ 
     NSError *error = nil; 
     if (![tempContext save:&error]) { 
      NSLog(@"an error occurred: %@", [error localizedDescription]); 
     } 

     [self.managedObjectContext performBlock:^{ 
      NSError *error = nil; 
      if (![_managedObjectContext save:&error]) { 
       NSLog(@"error in main context: %@", [error localizedDescription]); 
      } 
     }]; 
    }]; 

所以这部分工作正常。我现在遇到的问题是,在另一个视图控制器中,我显示这些保存的路由,路由来自self.managedObjectContext,我的主要上下文。所以在我显示保存的路线后,如果他们选择了它,那么它会返回到地图,以便他们可以添加更多。我这样做,我的故事板与此:

if ([destination respondsToSelector:@selector(setManagedObjectContext:)]) { 
     [destination setValue:_managedObjectContext forKey:@"managedObjectContext"]; 
    } 

但是现在,当我试图调用[self.route addAddressAnnotationsObject:anAddress];因为self.tempContext比路线的背景不同,我不能添加。我也不能仅仅说主要背景是现在的温度背景。有关我应该如何去做这件事的任何想法?提前致谢。

回答

0

self.route位于self.managedObjectContext,但anAddress位于self.tempContext。为了解决这个问题,你必须得到的self.routeobjectID,然后在self.tempContext与用它来查找对象:

- (NSManagedObject *)existingObjectWithID:(NSManagedObjectID *)objectID error:(NSError **)error 
+0

这并不在我的情况下工作,因为tempContext并不在我的SavedRoutesViewController存在。也许这就是我遇到的问题。但基本上,tempContext只存在于我想创建一个新对象的时候,所以如果用户从不决定保存任何东西,那么tempContext就会消失。只有当它们保存时,对象是否存在于self.managedObjectContext中。所以当我来自SavedRoutesViewController时,我保存的路由只能来自self.managedObjectContext,而不是tempContext。所以也许有更好的方法来设置呢? – Crystal

+0

为了保持一致,您在显示地图的View Controller中使用的所有对象应该位于'tempContext'中。我不知道你的代码是怎么样的,但你在这个View Controller中的流程可能如下所示:创建'tempContext',然后1)在其中创建新的托管对象(route),或者2)在'tempContext'中找到路由用户在tableView中选择(正如我在答案中所示)。 –

相关问题