Undo core data managed object

core-data, ios, iphone, objective-c

Solution

As mentioned earlier, you can use an undo manager. Or, you could simply use a separate ManagedObjectContext, and do all your changes in there. If you decide to keep them, save the context. If not, simply discard it. A MOC is just a scratch pad for work, and has no impact on the underlying database until saved.

You can't really "detach an entity" but you can cause a managed object to turn back into a fault, losing any changes that have not been saved.

[managedObjectContext refreshObject:object mergeChanges:NO];

Snipped from the documentation...

If flag is NO, then object is turned into a fault and any pending changes are lost. The object remains a fault until it is accessed again, at which time its property values will be reloaded from the store or last cached state.

Problem

I have this code: ``` Store* store = [NSEntityDescription insertNewObjectForEntityForName:@"Store"]; store.name = @"My Company" ... ``` Now the store is managed in the context and will be saved when the context is saved, but I have a button where the user can cancel the form where data is collected. How do I undo or remove this from the context? Or am I thinking wrong?

Original source