Dipen Panchasara
Dipen Panchasara

Reputation: 13600

Core Data : Add relation object to existing object

I have following entities in my core data

where relationships are as below.

Departments are already inserted in core data. When a new message arrives i insert it into core data and add Department relation but app crashes with following error.

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

following is my code snippet to set message object

NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:context];

// find department object from core data.
Department *objDepartment = [self findDepartmentByDepartmentId:dict[kDepartmentId]];
// Create new message object
Message *objMessage = [[Message alloc] initWithEntity:entity insertIntoManagedObjectContext:context];
    // *** Establish relation with department ***
    if(objDepartment != nil)
    {
        // app crashes here...
        [objMessage setDepartment:objDepartment];
    }
    [objMessage setLastUpdatedTime:[NSDate date]];
}

// *** Set other values in message object ***

Note : Everything is done using Parent-Child context in core-data.

Any suggestions or help would be appreciated.

Upvotes: 1

Views: 481

Answers (2)

Krzysztof
Krzysztof

Reputation: 1471

Looks like Department was fetched from Different context, you need to get department object from same context. Try if this works:

Department *objDepartment = [self findDepartmentByDepartmentId:dict[kDepartmentId]];

// Get department in in current context 
NSError *error = nil;
objDepartment = [context objectWithID:objDepartment.objectId error:&error]

Upvotes: 1

Vidhyanand
Vidhyanand

Reputation: 5369

You need to fetch specific record for updating using NSFetchRequest

// find department object from core data.
Department *objDepartment = [self findDepartmentByDepartmentId:dict[kDepartmentId]];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:@"Message"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:@"Message==%@",txtMessage]; // If required to fetch specific vehicle
fetchRequest.predicate=predicate;
Message *objMessage = [[context executeFetchRequest:fetchRequest error:nil] lastObject];
if(objDepartment != nil)
{
   // app crashes here...
   [objMessage setDepartment:objDepartment];
}
[objMessage setLastUpdatedTime:[NSDate date]];
NSError *error;
if (![context save:&error]) {
     NSLog(@"Whoops, couldn't Update: %@", [error localizedDescription]);
  }
  else{
        //updated successfully
}

//For inserting new record

Message *objMessage = [NSEntityDescription insertNewObjectForEntityForName:entityName inManagedObjectContext:context];

Hope it helps you...!

Upvotes: 0

Related Questions