Question

I am trying to make an application where a user can edit attributes of a managedObject in a view, and select either Done to persist the changes, or Cancel to undo the changes.

To implement this behavior, I plan to do the following-

  • When the view controller is loaded to edit the managedObject, create a backupManagedObject which is a clone of the original managedObject.
  • This backupManagedObject is created in a separate child ManagedObjectContext.
  • Let the user edit the original managedObject.
  • If:
    • Done is pressed, the original managedObject is persisted, and backup is deleted
    • Cancel is pressed, the backupManagedObject is cloned into original managedObject and the backup is deleted

My question is, once I am done with the backupManagedObject, how can I delete the childManagedObjectContext which will have no more managed objects and I don't plan to use them anymore (for every new view controller, I plan to just create a new child managed object context and destroy it once view controller is done).

Was it helpful?

Solution 2

In general, a managed object context is release the same way any other object in Objective-C is released and deallocated.

If you are using ARC, simply set the property to nil when you no longer need it and it will be destroyed along with any unsaved changes.

However, your approach for this problem is a bit complicated.
You could simply create a new "editing" child context, fetch the objects you like to edit in that context and make changes to the objects.

If the user decide to commit the changes, save the context (up to the store), and if not, simply destroy the context.

OTHER TIPS

You should do this the other way around:

When you load your editing View Controller, create new Managed Object Context that is the child of your main one, let's call it the editingMOC.

Do the edits to the editingMOC, and if you want to persist them, save the editingMOC (this will propagate changes to the mainMOC), and then save the mainMOC to save the data to the persistent store.

If you wish to discard the changes done to the editingMOC, simply do not save them and let the context get dealloc'd.

An easier way is to simply create the view and populate the UI controls (text fields, etc.) using data from the NSManagedObject attributes. If the user makes any edits then set a flag so you know if changes are made and then when they select Done update the NSManagedObject attributes using values from the UI controls and save the MOC. If they select Cancel then don't do anything.

See this link for a video showing an app using a similar approach for editing Core Data records on iOS. The OSX app uses standard NSPersistentDocument undo manager.

http://ossh.com.au/design-and-technology/software-development/uimanageddocument-icloud-integration/os-x-and-ios-app-integration-with-core-data-and-icloud/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top