Search code examples
ioscore-datansmanagedobjectcontext

create entity in child NSManagedObjectContext with relationship to parent entity


I am creating temp context for edit entity:

    NSManagedObjectContext *parent = [Default managedObjectContext];//my main managed context
    NSManagedObjectContext *_createNewContex = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_createNewContex setParentContext:parent];

In the _createNewContex I am trying to create My temp entry for editing.

   MyTempEntry *entry = [MyTempEntry createInContext:_createNewContex];

It is created ok but if try to assign relationship for entry from parent context:

  entry.entryFromParent = parentEntry;

I have error:

* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'entryFromparent' between objects in different contexts


Solution

  • you can't use object's between context's. you'll need to lookup the object on the secondary context using its objectID, or some other value.

    that object from the secondary context can then be used to create the relationship.

    something like the rough code below

    NSManagedObjectID *objectID = [parentEntry objectID];
    
    id newContextParentEntry = [_createNewContext objectWithID:objectID]; 
    
    entry.entryFromParent = newContextParentEntry;