The third installment in the multi-part series covering the various design patterns used in iOS. The Model View Controller (MVC) design pattern separates aspects of an application into three distinct parts and defines how the three communicate.
As the name implies the application is divided into three distinct parts: Model, View and Controller. The main purpose for MVC is reusability where you can reuse the same model for different views.
The model contains the data. For example, a
Book object contains information regarding the book such as: title and author. In addition, the Book object could be related to other objects establishing a one-to-one or one-to-many relationship. For example, the
Book object could relate to a
Category object, wherein one
Category can contain multiple
Book objects. The model objects obtain data either from a database or files, which could be located locally or externally. The model does not talk directly to a view, instead is made available to a controller which accesses it when needed. In iOS, a model is usually a subclass of
NSObject or in the case of Core Data (an iOS framework that helps save data to a database locally on the device)
NSManagedObject. As with any model object it contains instance variables and getter / setter methods. Most object-oriented languages have a mechanism to provide encapsulation, in iOS a
property provides encapsulation and the keyword
synthesize automatically generates the getter and setter methods. In the case of
Book you would have methods such as
The view displays information contained in the model. For example, the view could display a list of
Books as mentioned in the above example. Although the view does not obtain the information directly from the model, it uses the controller as a mediator which instructs it when and what to display. In iOS, most views subclass from
UIView which provides the capability for handling touch events and drawing. The UIKit framework contains classes to draw typical interface elements such as tables (lists), buttons, textfields, sliders and more. Below is a list of books displayed using the class
Finally, the controller is responsible for accessing data from the model and displaying it on the view. The same controller can be used to intermediate between several views and models. The controller monitors user interaction with the view and communicates any changes to the model. On the other hand, changes to the model are observed by the controller and subsequently reflected in the view. The controller is also where most of the application lies. In iOS, the controller is generally a subclass of
UIViewController that manages a view, it is also responsible for responding to delegation messages and target-action messages. Below you have a
UITableViewController which is a subclass of
UIViewController that manages a
If you are interested in learning more do check out the iOS development course.