I know that several issues possibly duplicated being, however, no pointed solution solved my problem, so I decided to post my specific case.
I'm working with CoreData in my application, and some objects are instantiated without being effectively saved on the ground, my startup code in these cases is as follows:
-(id)initEntity:(NSManagedObjectContext*)context{
AppDelegate appDelegate * = [[UIApplication sharedApplication] delegate];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Endereco" inManagedObjectContext: appDelegate.managedObjectContext];
self = (Endereco*)[[Endereco alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
return self;
}
However, an attribute of this object is the municipality that is already saved on the base, and is selected by a ActionSheet:
if (actionSheet == actionSheetMunicipios) {
Municipio *municipio = [municipios objectAtIndex:buttonIndex-1];
endereco.municipio = municipio;
[textMunicipio setText:endereco.municipio.nome];
}
in line
endereco.municipio = municipio;
I get the following error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship' municipio 'between objects in different contexts.
The error is clear, I am trying to establish a relationship of objects with different contexts, but in my case, in which the Parent object is not saved on the base, and that the child object is already there, how could I solve?
I managed to solve the problem by adding the Endereco in the managedContext of the Municipio:
if (actionSheet == actionSheetMunicipios) {
Municipio *municipio = [municipios objectAtIndex:buttonIndex-1];
[municipio.managedObjectContext insertObject:endereco];
[endereco setMunicipio:municipio];
[textMunicipio setText:endereco.municipio.nome];
}
I do not know if it's the best solution, but it worked perfectly in this case.