Chris Dzombak

sharing preview •

Parent-Child Communication in a Coordinator/View Model Application

Parent-Child Communication in a Coordinator/View Model Application

I received an interesting question via Twitter last week:

It took me a few days to find the time to write a good answer, and I wanted to post something on the subject here for future reference:

View controller containment can be used for a number of distinct purposes; therefore it depends on the nature of the parent/child relationship.

If the parent is something like a navigation controller (eg. a generic container) and the child is one of your application view controllers, then the parent view controller would talk to the coordinator, who would talk to the child view model.

(It would be rare, though, to have a UINavigationController need to communicate something to a child view model; normally it would take the coordinator as its UINavigationControllerDelegate and the coordinator would take any necessary actions — including communicating with child view models — in response.)

If the parent and child together are composed into a single “application” view — rather than a “container” like a navigation controller — then the parent view model might well know about the child view model and even hold a reference to it. They might even be the same object, though there would be separate protocols for the parent’s and child’s view models. Then the parent view controller might call to its view model, which would communicate to the child’s view model, no need to get the coordinator involved.

It’s hard to answer in general. Just be sure to consider where divisions of responsibility lie, and what types should be generic & reusable. Don’t share up to the coordinator if you don’t need to, but also don’t let a generic parent view controller know about the types of view controller it may contain.