Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot add parentContext to NSManagedObjectContext, context already has a coordinator

I have a view where I retrieve a saved Entity (Route *) from the main NSManagedObjectContext. I want to import that into a tempContext. Following Marcus Zarra's examples, I do this:

    NSManagedObjectContext *moc = _route.managedObjectContext;
    NSManagedObjectID *routeId = [_route objectID];
    NSPersistentStoreCoordinator *psc = moc.persistentStoreCoordinator;
    self.tempContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [self.tempContext setPersistentStoreCoordinator:psc];
    NSManagedObject *localRoute = [self.tempContext objectWithID:routeId];
    [localRoute moToDictionary:localRoute];
    self.tempContext.parentContext = moc; // crashes here

Everything is good until I try to set the parentContext of my tempContext to the main MOC. I get the error:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Context already has a coordinator;  cannot replace.'

I understand it's telling me that I cannot change the persistentStoreCoordinator. However I'm nto sure why it's telling me that. When I set a breakpoint, the tempContext is at a different memory addres than the main moc. Also, the self.tempContext.parentContext is nil. So I'd think if it's nil, I could set the nil parameter to the moc, but it crashes. Any thoughts? Thanks in advance!

like image 581
Crystal Avatar asked Feb 15 '23 01:02

Crystal


1 Answers

For a managed object context, you can

  • either set the persistent store coordinator, to get a second independent MOC with the same store,
  • or set the parent context to get a child MOC,

but not both.

like image 129
Martin R Avatar answered Apr 09 '23 10:04

Martin R