Is it right having ViewControllers with a lots of code? Is it right having ViewControllers with a lots of code? ios ios

Is it right having ViewControllers with a lots of code?


One of the most common causes of large view controllers that I have seen, is lack of separation b/w Model and Controller in MVC architecture. In other words, are you handling your data in your view controllers?

If yes, rip out the model component from VC and put it into separate class. This will also force your thinking towards a better design.

For reference, In View Controller:

  • Handling of all changes in the UIView and the UI elements contained within.
  • All animation, transitions and CALayer operations.

In Model:

  • All processing of data, including sorting, conversion, storage, etc.


IMHO, 700 lines is not (yet) huge for iOS code, I've seen and handled much worse. Of course, if all your VCs are this big, you have a problem.

You should definitely use and abuse #pragma mark, it's very useful under Xcode at least.

Then if you find you got too much code in one file, you can extract functionality to classes or categories, as better fits.

Creating classes can be very rewarding in the long term to manage recurring tasks in projects (ie connecting to webservice, parsing XML/JSON, interacting with SQLlite, logging, etc...). If you are doing recurrent iOS programming, you can create a 'common' library of useful code that way.

Creating categories, especially on UIViewController can help reducing boilerplate code that takes a lot of place. You can (and probably should) also create a common base UIViewController for your app, that will handle stuff like rotation, maybe logging, navigation, etc... in a centralized part of the code.


You should try to identify what your ViewController is really doing.

If you can separate some concerns you can move them to classes of their own. Find out which properties and ivars are used by the viewControllers methods. If you can find a subset of functions, that use a common subset of ivars/properties, these together are very likely to become a class of their own. The controller would then own such a new class and delegate work to this.

If your ViewController is managing some sort of state, eg. you find the same switch statement or if-chain in 2 or more methods the STATE pattern could make your VC much more readable. But basically you could use any pattern that helps to reduce the VCs responsibilities.

IMHO the ViewController is the place were you would connect the model to the views. Propagating model changes into views and handling user interaction with the views are the only things, that should happen there. All other responsibilities, like calculation, network transfer, parsing, validation... should happen in different classes the VC uses.

You might like the book Clean Code by Robert C. Martin. He explores in depth how code could be structured to increase it's readability and reusability.