Angel G. Olloqui
It has been a long time since I started with the MVC post series
. It is not that I didn’t want to write about it, but by the time I was supposed to start with this post Objc.io
came with a very good issue on View Controllers
, which made my post almost irrelevant as most of the ideas were already mentioned there. Anyway, after receiving quite a lot of messages asking for this post, I finally decided to spend some time and try to address some new points and explain those that are important. That being said, if you haven’t read objc.io issue do not hesitate because it is worth the time and an excellent complement for this post.
The controller role
In MVC, the Controller is the part of your software that communicates
layer with your View
layer, and it is by far the most abused role in iOS project. But lets first define how a good controller should look like:
A good controller should know how to request data to the model but not its internal details or how to fetch it; it should know what view to use but not how to draw it; it should be the one receiving events from one layer and passing messages to the other layer but not the one creating the events. In brief, a Controller should be the glue needed to connect the Model and the View, but ideally it should not do anything else than that.
However, in iOS projects we often find controllers that make lot more duties that the ones they should. This is not a coincidence: delegation patterns used in most of Apple’s components can be easily implemented on controllers, and the UIViewController API exposes methods like viewWillLayoutSubviews that should concern the View role only. Even the UIViewController name denotes this lack of real distinction between views and controllers!
Nevertheless, writing good controllers make your code lot more reusable (not only the controllers but the other layers also), easier to test, more maintainable and more flexible. So, lets review some important guidelines: