Reputation: 9157
I'm instantiating a NSManagedObjectContext
object at the Application delegate level and sharing it across all my UIViewController
s. Here's the code that I use to access it in one of my View Controllers:
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
modelObj = (Model *) [NSEntityDescription insertNewObjectForEntityForName:@"Model" inManagedObjectContext:[appDelegate managedObjectContext]];
Now in this screen, I have a UITableView
with 9 rows & each cell has a UITextField
. As the user inputs values into the textfields, I assign them into modelObj
. Now, my user has an option to cancel out and discard all the changes or save them to disk. I have the save code working fine. But in the case when a user tries to discard the changes, I'm not sure what to do. There doesn't seem to be a [managedObjectContext discardChanges]
method to throw them all away.
I can think of a couple of ways of solving this.
NSManagedObjectContext
for each controller instead of sharing one across the application. NSString
s in my code and save user values in them and call insertNewObjectForEntityForName:
only if the user clicks save.Which way is the right one? Or is there a way to make NSManagedObjectConext
discard all the changes that were made to it?
Thanks,
Teja.
Upvotes: 11
Views: 7795
Reputation: 8292
NSManagedObjectContext has a simple method for this:
[managedObjectContext rollback];
This method "removes everything from the undo stack, discards all insertions and deletions, and restores updated objects to their last committed values." (documentation)
Unless I'm missing something, that should give you everything you need.
Upvotes: 44
Reputation: 60150
You might be looking for -refreshObject:mergeChanges:
- the docs say that it resets an object from the persistent store, and if you pass NO
as the second argument, you can choose not to reapply changes that have been made.
This will likely require you to store a set of objects that you have changed (for the first argument), then clear that set when you commit changes in your context to the store. This should be a pretty trivial addition, though.
Upvotes: 2