Reputation: 17159
I have two NSManagedObject
subclasses. Flight
and Aircraft
. Each Flight
is associated with one Aircraft
.
When the user is creating a Flight
, I only do the following:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Flight" inManagedObjectContext:self.managedObjectContext];
self.flight = [[Flight alloc] initWithEntity:entity insertIntoManagedObjectContext:nil];
Create the object but do not insert it into the managedObjectContext
until the user is certain they want to save it. If they save, I insert the object, if they cancel, its discarded.
This was a great solution, until now. When the user selects an Aircraft
, I do this:
[self.flight setAircraft:aircraft];
However, because the flight
object has not been inserted into the managedObjectContext
the app crashes with this error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'aircraft' between objects in different contexts
That makes sense. And if I insert the flight
object as soon as its made, this error doesn't occur. But then it creates the problem that, what if the user cancels and doesn't want this flight object any more?
Upvotes: 2
Views: 573
Reputation: 1453
Why not just use a set of parent-child contexts. Keep inserting everything in the child context. If the user finally selects 'Save', call save: selector on child context first (and then parent context too). If the user finally selects 'Cancel', call rollback: selector on child context.
http://www.cocoanetics.com/2012/07/multi-context-coredata/
Upvotes: 1
Reputation: 50089
use a temporary context for the aircraft and the flight .. a scratch context
THAT is recommended way AFAICS
if the user hits save, save the context, else .. do nothing
Upvotes: 0
Reputation: 4953
It sounds like in the end, the user will either save these changes or cancel them, and no other CoreData operation will happen in the interim. If that's true, when you're ready to save, call NSManagedObjectContext's
save:
then. Otherwise, call its rollback
and all the changes in the undo stack (i.e., everything that you've changed since the previous call to save:
, such as the creation of flight
) will be undone.
Upvotes: 0