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.
One approach to delete everything and reset Core Data is to destroy the persistent store. Deleting and re-creating the persistent store will delete all objects in Core Data.
A managed object context is an instance of NSManagedObjectContext . Its primary responsibility is to manage a collection of managed objects. These managed objects represent an internally consistent view of one or more persistent stores.
NSManagedObjectContext is not thread safe The NSManagedObjectContext , which gets created as part of an NSPersistentContainer from your AppDelegate , is tied to the main thread.
An object space to manipulate and track changes to managed objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With