Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData: Clear changes from NSManagedObjectContext

I'm instantiating a NSManagedObjectContext object at the Application delegate level and sharing it across all my UIViewControllers. 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.

  • Create a new instance of NSManagedObjectContext for each controller instead of sharing one across the application.
  • Or, I could create a bunch of NSStrings 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.

like image 469
Tejaswi Yerukalapudi Avatar asked Dec 08 '11 00:12

Tejaswi Yerukalapudi


People also ask

How delete all data from Core Data?

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.

What is the purpose of NSManagedObjectContext?

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.

Is NSManagedObjectContext thread safe?

NSManagedObjectContext is not thread safe The NSManagedObjectContext , which gets created as part of an NSPersistentContainer from your AppDelegate , is tied to the main thread.

What is NSManagedObjectContext in Swift?

An object space to manipulate and track changes to managed objects.


1 Answers

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.

like image 105
Tim Dean Avatar answered Sep 27 '22 18:09

Tim Dean