I am getting this nasty crash and error.
The crash occurs when this code runs:
Address *address = [[Address alloc] initWithEntity:[NSEntityDescription entityForName:@"Address" inManagedObjectContext:managedObjectContext] insertIntoManagedObjectContext:nil];
//Crashes here!
[person addAddressObject:address];
Illegal attempt to establish a relationship 'person' between objects in different contexts
The entire console error is below.
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'person' between objects in different contexts (source = <Address: 0x1f87e270> (entity: Address; id: 0x1f87e2b0 <x-coredata:///Address/t748EE284-0311-4489-9654-1D902EB0D4CC2> ; data: {
addressLine1 = "";
addressLine2 = "";
addressLine3 = "";
city = "";
country = "";
person = nil;
state = "";
title = "";
zip = "";
}) , destination = <Person: 0x1ed9e1e0> (entity: Person; id: 0x1ed9c710 <x-coredata://ED0283A9-A847-407E-BFEC-CF2BF85C6A9C/Person/p1> ; data: {
address = (
"0x1f87e2b0 <x-coredata:///Address/t748EE284-0311-4489-9654-1D902EB0D4CC2>",
"0x1ed93e70 <x-coredata://ED0283A9-A847-407E-BFEC-CF2BF85C6A9C/Address/p1>"
);
favourite = nil;
firstName = Josh;
lastName = Kahane;
}))'
I have no clue how to fix this. Presumably it thinks there is two different managedObjectContexts? However, in my app I only ever reference that made in my app delegate like so (run at viewDidLoad):
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(@"After managedObjectContext: %@", managedObjectContext);
}
Any ideas as to where to start looking for the discrepancies? Thanks.
EDIT:
New discovery. Just before the app crashes, I’ve NSLogged both the address and person managed object contexts. Turns out the address context is (null), even if I run the check right before hand to set the context if its nil.
You’re inserting it into a nil
managedObjectContext.You’ll need to insert the object into the
NSManagedObjectContextthat you use for the entity. i.e.managedObjectContext.In the alloc init of the Address object.
Reading your comment in the OP.
You should either…
Save all the required values and then at the point on confirmation create the Address object and insert it all in one go.
Or…
Create the object and insert it creating all the relationships and then if the user presses cancel just delete the object.
I’d do one of these two to avoid this error.