Search code examples
core-datasavensmanagedobjectcontextrollback

Do I need multiple contexts to update independent objects?


I have a view controller which updates a single managed object (type A) selected from a preceding table view. However, there is a button on the VC which loads another view controller to update a second managed object (type B). Both view controllers have Save and Cancel buttons in the normal way.

My requirement is that I can commit (save context) the changes to B and unwind the VC to continue with the edits to A. The A changes may get saved or cancelled but I want B to remain changed.

Conceptually, this would seem to require independent contexts at the same level. i.e. I cannot use a child context for B as those changes still get rolled back if the A update is cancelled.

Can I create two main contexts, or do I need to create two children of my main context? I could then save or rollback the two child contexts as required and save the main context regardless. Is there a better way to do this?

Thanks,

Julian


Solution

  • Because each object's changes could be canceled but are otherwise independent. You will want to use a child context of your main context for each of them. Contexts, while not cheap, are not particularly expensive either. Your use of child contexts to allow easy cancelation of changes is a standard and encouraged pattern.