I’m sure this must be a common pattern in iOS apps. I have a list controller that displays a list of items. I have a segue (using storyboards) to a modal for adding a new item, where I just collect the name. Once dismissed, I will return to the list, update it to include the added item, and do a couple of other small things (lets say log something for simplicity). Crucially, I need to log something that is part of the list controller, not the modal controller.
At some point along the way I also need to insert the new item in to my managed object context.
I have tried two approaches:
1) pass the ManagedObjectContext into the modal’s controller using PrepareForSegue. Insert the new item into the context from the modal’s controller. Works great to this point. But now I want to refresh my view and write my log lines. I can’t put these in viewWillAppear because I don’t want the lines to be logged at first load or any other time, only after returning from the modal.
2) make the list controller a delegate of the modal controller so that I can do all of my work in the list controller itself, and only call the list controller’s code when the save button is used in the modal (averts the issue with running on every load). But since Item is a managed object I can’t create it without reference to the context, which the modal controller knows nothing about, so I can’t insert the item in the modal. I also can’t pass it to the delegate and insert it in the List controller, since there is no way to create a managed object without the context.
What is the established standard for this kind of flow? Maybe I should be using a combination of both – pass along the context to the modal controller so it can handle it’s own insert, and then call the delegate code in the list controller just to handle the logging?
A combination of 1) and 2) is what I use. Create a new managed object in prepareForSegue and pass this to your modal view controller. Set your list controller as the delegate of the modal view controller, and update your logging in the delegate methods.
There is no need to have any core data heavy lifting in the modal, it doesn’t need to know those things.
(In fact, if you’re only setting a name in the modal it doesn’t even need to know about the object, you could just return a string, but if you do pass the object it gives you more flexibility if you decide to make it a bit more functional.)