Join Ron Buencamino for an in-depth discussion in this video MVC fundamentals, part of Understanding the Model-View-Controller Design Pattern in iOS.
- View Offline
- When we talk about the Model-View-Controller design pattern, otherwise known as MVC, we are referring to a high-level design pattern that concerns itself with the global architecture of an application. Within this design pattern, objects are classified by the type of role that they play within the system. There are three role types that an object can fall into, model, view, or controller. The separation of these roles also defines how the three communicate with one another.
As we can see from this diagram, we have the three separate roles and what each is going to be responsible for. We'll go more into what defines each of these later on in this lesson, but for now we're just going to get a basic understanding. Models or objects that contain data and are described by the attributes that make them up. For example, we could model a book object that has its own attributes such as a title, author, genre, identification number, and so forth.
Views are used to display information contained within a model. Or they are used to receive user input and display output. Views are what the user interacts with in your program. Controllers are used to access data from the models and display them in the view. They tie the model and the view together. Again, we'll go more into detail on each of these roles later on. But for now let's use this as a basic understanding of how things work. So, if we were to receive user input from within our view, that input gets sent from the view to the controller.
Which then proceeds to update our model. And then once our model finishes updating, it notifies the controller that this has been completed. And then the controller in turn updates the view to reflect the changes in the model. As you can see there's a logical flow that separates each of the roles. With the controller facilitating things between the model and the view. But why would this benefit us? Well, it should be stated that in object-oriented programs, like the ones we create using x-code, they benefit tremendously from MVC in several ways.
First, it allows our objects to be more reusable. Which is efficient for our code, and is also paramount to developing object-oriented programs also because of the clear distinction in the roles, interfaces tend to be better defined which leads to our code becoming easily extensible down the line in comparison to other applications. And lastly, the Cocoa framework is based on MVC. So if you want to create custom objects within your applications, it's required that your objects adhere to this design pattern.