Coordinator : the Pattern · the Library · the Class · recommended Implementation
(and why you need to use it)
UIViewController
, in essence, is very straight-forward implementation of MVC pattern: it is mediator between data model / data source of any kind and one UIView
. It has two roles:
- receives the data and configure / deliver it to the
view
- respond to actions and events that occurred in the view
- route that response back into data storage or into some other UIViewController instance
No, I did not make off-by-one error. The 3rd item should not be there but it is in the form of show, showDetailViewController, performSegue, present & dismiss, navigationController, tabBarController etc. Those methods and properties should never be found inside your UIViewController code.
UIViewController instance should not care nor it should know about any other instance of UIVC or anything else.
It should only care about its input (data) and output (events and actions). It does not care who/what sent that input. It does not care who/what handles its output.
Coordinator is an object which
- instantiates UIVCs
- feeds the input into them
- receives the output from them
It order to do so, it also:
- keeps references to any data sources in the app
- implements data and UI flows it is responsible for
- manages UI screens related to those flows (one screen == one UIVC)
Login flow that some AccountCoordinator
may implement:
- create an instance of
LoginViewController
and display it - receive username/password from
LoginViewController
- send them to
AccountManager
- If
AccountManager
returns an error, deliver that error back toLoginViewController
- If
AccountManager
returns aUser
instance, replaceLoginViewController
withUserProfileViewController
In this scenario, LoginViewController
does not know that AccountManager
exists nor it ever references it. It also does not know that AccountCoordinator
nor UserProfileViewController
exist.