Reputation: 503
I have an application listening to server events through a websocket. When the server sends a specific event, I create a Notification
which is a subclass of NSManagedObject
. I later display it in my main view controller.
In a view controller (let's call it ObjectViewController
), I have this code :
- (void)viewDidLoad {
[super viewDidLoad];
[((AppDelegate *)UIApplication.sharedApplication.delegate).managedObjectContext.undoManager beginUndoGrouping];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
AppDelegate * delegate = ((AppDelegate *)UIApplication.sharedApplication.delegate);
if (something) {
[delegate saveContext];
} else {
[delegate.managedObjectContext undo];
}
}
It allows me to undo all operation done to several NSManagedObjects
of different types when I click the cancel button.
Now the problem is, when I am in this view and I receive a notification, the Notification
object is removed from CoreData if I cancel the object changes.
Is there a way to force CoreData to save ONE notification while the other NSManagedObjects
remain in the undo group ?
Upvotes: 0
Views: 126
Reputation: 28419
When you save a context, it saves everything in the context.
IMO, a better approach would be to use a separate NSManagedObjectContext
as a "scratchpad".
Basically, your view controller will create its own context, either as a child of the main context, or connected directly to the main context's persistent store coordinator (if the latter, you need to merge saved changed).
This use case, however, is probably best served by creating a child context.
This way, your "editing context" is separate from the main context. When the view controller goes away, you can save the context, or simply do nothing and let it dealloc.
Thus, you can still have changes going on in your "main context" and anything done in the "editing context" only happens if you choose to save the context.
You can then just not even use the undo manager, as the temporary context is doing that work.
EDIT
After looking at the apple doc, to create a new context as a child of the main context, I just have to set its parentContext attribute ? I don't know how I lived without knowing this... so useful ! – Sunder
To create it, yes, that's all you have to do. There are some drawbacks to using it, but there are usually corner cases. As long as you are not creating new objects in the child context and passing their object-ids to another MOC, you should be fine.
Simply make your changes, and if you want to share them with the parent, just save to the parent. Note, however, that saving from a child to a parent just "copies" the object changes into the parent. The parent context must still save its context for the changes to make it to the store.
Upvotes: 1