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?
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.
Snipped from the documentation...
Core Data has built-in support for undo, so you can undo individual changes by sending the
-undo
message to the context:It also supports
-redo
. You can undo all changes up to the most recent save using the-rollback
method:as indicated in @melsam's answer.
Also you could save all data from the user in an array and when the user is ready, you only have to save the array to core data.
Undo
works only when I create aundoManager
(Swift 5):After this configuration you can undo a last change: