Search code examples
iosobjective-ccore-datansmanagedobjectnsmanagedobjectcontext

Deleting NSManagedObjectContext


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).


Solution

  • 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.