2

I use CoreData to manage my application data model. I use child managed object context in my editing view controller so that I can ether save or discard the changes made by the user.

I create the child context as follows:

NSManagedObjectContext* mainMoc = <my main context>;
NSManagedObjectContext* editMoc = [[NSManagedObjectContext alloc] init];
editMoc.parentContext  = mainMoc;

If the user taps "done" button, I save changes as follows:

[editMoc save:&error]

If the user taps "cancel" I just discard the editMoc context.

Here is the question: I use State Preservation and Restoration throughout my app, and I want to save the editMoc context with the changes for further restoration, when the app goes to background. I don't want to merge editMoc with the mainMoc, because the user did not decide yet whether to save or discard the changes.

I tried using the NSCoding protocol to serialize the editMoc, but the registered objects are not saved this way. I also tried to change the parentContext, but this throws an exception.

I believe there should be a nice way to accomplish the above task, as it is a common practice to use child contexts and state preservation.

My project runs on iOS 6.0 and above.

Denis Krivitski
  • 654
  • 8
  • 11

1 Answers1

2

There is no way internal to Core Data to save those objects. What you can do, however, is ask that moc for all of its unsaved objects (-updatedObjects, -insertedObjects, -deletedObjects) and then iterate over them and save them to disk individually. I would suggest saving them in an intermediary format like JSON or plists.

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182