I am trying to get my head around the core data and I am trying to implement a small to-many relationship but I keep getting the error below:
I have two NSManagedObject classes (Groups and Contacts) created by Xcode's data model with a to-many relationship.
@implementation Groups
@dynamic groupId;
@dynamic groupName;
@dynamic groupContacts;
@end
@implementation Contacts
@dynamic firstName;
@dynamic lastName;
@dynamic userId;
@dynamic belongsToGroup;
I have contacts data as an array of dictionaries and I am doing the following:
self.localGroup = [NSEntityDescription insertNewObjectForEntityForName:@"Groups" inManagedObjectContext:self.scratchPadContext];
self.localGroup.groupName = @"Some Name";
for (int i = 0; i < [self.ContactsData count]; i++) {
Contacts *contact = [NSEntityDescription insertNewObjectForEntityForName:@"Contacts" inManagedObjectContext:self.scratchPadContext];
NSDictionary *obj = (NSDictionary *)[self.ContactsData objectAtIndex:i];
contact.firstName = [obj valueForKey:@"firstName"];
contact.userId = [obj valueForKey:@"email"];
[self.localGroup addGroupContactsObject:contact];
}
if (![self.scratchPadContext save:&error]) {
NSLog(@"Errror saving Group ********************************* %@, %@", error, [error userInfo]);
}
I get the following Error:
[4459:15503] Errror saving Group ***************** Error Domain=NSCocoaErrorDomain Code=134030 "The operation couldn’t be completed. (Cocoa error 134030.)" UserInfo=0x85e0ab0 {NSAffectedObjectsErrorKey=( " (entity: Groups; id: 0x838d020 ; data: {\n groupContacts = nil;\n groupId = 0;\n groupName = Some Name;\n})" ), NSUnderlyingException=Cannot update object that was never inserted.}, { NSAffectedObjectsErrorKey = ( " (entity: Groups; id: 0x838d020 ; data: {\n groupContacts = nil;\n groupId = 0;\n groupName = Some Name;\n})" ); NSUnderlyingException = "Cannot update object that was never inserted."; }
If I comment out the relationship part and just save the group name, it works fine. So, I guess the problem is with the relationship data but I cannot figure out what. Can anyone please point me to where I could be doing it wrong?
[EDIT]:
When I add
contact.belongsToGroup = self.localGroup;
I get the following error even though I am using one MOC. I cannot understand where the mistake is. I would greatly appreciate if anyone can shed some light on this.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'belongsToGroup' between objects in different contexts (source = <Contacts: 0x86926a0> (entity: Contacts; id: 0x8692700 <x-coredata:///Contacts/t2548922E-A0C6-4E3C-9760-3265954764E73> ;