You’re previewing Ry’s Cocoa Tutorial

The MVC Pattern

Model-view-controller (MVC) is a design pattern for creating well-organized applications. It separates an application’s functionality into 3 distinct layers:

Model The abstract data that is manipulated by the application.
View The graphical objects that define the user interface.
Controller The code that glues the model and view layers together.

We already saw examples of the view and controller layers in the previous chapter. MainMenu.xib and the Button/Label components comprised the view layer, while the AppDelegate class served as the controller. The model layer, however, was completely missing.

In a typical Cocoa app, the model layer consists of custom classes that represent the different types of data that the application works with. For example, if you’re building a game, you might have a CharacterData class that defines all of the properties and behaviors of a character in the game. Additionally, you might have a LevelData class that represents a world for that character to interact with.

The model-view-controller design pattern

Instead of tying the model objects directly to the view objects that display them, the MVC pattern uses a separate controller object as an intermediary. When the user interacts with the app, the view layer notifies the controller layer. Then, the controller interprets that input and updates the model data accordingly. On the flip side, when the model data changes, it notifies the controller, which updates the UI components to match.

The result is a modular architecture that makes it very easy to reuse both your model data and the view objects. To fully appreciate this, consider the built-in Label component, which is part of the view layer. It can be used to display a character’s name, an enemy’s health, the user’s score, a message from another user, or any other kind of information you could imagine in an OS X game. All you need is a controller to connect the Label to the desired property of a model object.

In this chapter, we’ll explore the MVC design pattern by building a simple volume slider. You’ll recognize the target-action and outlet patterns from the previous chapter, but the addition of a model layer will give us the standard architecture for virtually every Cocoa application.

Sorry, this is the end of the preview. To read the rest of this chapter, you’ll need to purchase Ry’s Cocoa Tutorial.

Mailing List

Sign up for my low-volume mailing list to find out when new content is released. Next up is a comprehensive Swift tutorial planned for late January.

You’ll only receive emails when new tutorials are released, and your contact information will never be shared with third parties. Click here to unsubscribe.