TweetFollow Us on Twitter

The Road to Code: Patterns in the Sky

Volume Number: 24 (2008)
Issue Number: 08
Column Tag: The Road to Code

The Road to Code: Patterns in the Sky

The Model-View-Controller Design Pattern

by Dave Dribin

Welcome Back

We've come a long way since the first Road to Code. We've covered Foundation and AppKit, the basic frameworks of Mac OS X, and we can write GUI applications. While we've covered the Objective-C language and classes that make up an application, we've glossed over a bit of history. How did Mac OS X applications evolve the way they have? Why did Apple's (and NeXT's) engineers create classes like NSApplication, NSView, and NSControl? The search for these answers takes us down a path the computing history.

Design Patterns

Ever since the dawn of computing, programmers have been trying to make their lives easier and more productive. Today we take high-level languages like Objective-C, C++, Java, Ruby, and Python for granted. Back in the day, programmers had to code in assembly language directly. Grace Hopper wrote the very first compiler in the 1950s to alleviate the pain of writing assembly language. In the 1970s, when the Unix operating system was originally being developed, the designers created their own language, called C, to help make Unix easier to port to new computer systems. C was one of the first and, in retrospect, is arguably the most successful high-level language. The benefit of C over assembly language was two-fold. First, the programmer could write code once that would run on multiple computer systems. All she had to do was recompile the C code for the target system and it would, if written properly, run without modifications. The other benefit of C code is that it was a lot more readable and understandable to the programmer. Both of these benefits greatly simplified the programmer's job.

C is still in active use today, either directly or in one of its derivatives forms, such as C++ and Objective-C. C also brought with it the ability to put commonly used code into libraries. Code - such as displaying text to the user and receiving input to the user and manipulating strings - can be re-used by many programmers and applications. The benefit is that each developer can spend their time writing their own application instead of having to re-invent the wheel, so to speak. Reusing code through libraries is also a big boon for the programmer.

But as good as reusing code through libraries is, it does have limitations. Sometimes, different applications perform many common tasks that may not be codified into libraries. Or sometimes these common tasks transcend the particular language you are using and apply to, say, any object-oriented programming languages. These higher-level reusable tasks are called design patterns. Design patterns are not unique to software development. The term "pattern" as a reusable idea originated from an architect named Christopher Alexander.

Software design has some similarities to traditional architecture and engineering, and design patterns are one of these similarities. The term design pattern in the software industry was popularized by the seminal book Design Patterns: Elements of Reusable Object-Oriented Software. The book was written in 1995 by four authors: Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides - now infamously known as the "Gang of Four". The Gang of Four (GoF) patterns book cataloged and described many design patterns that the authors used, or had observed in object-oriented applications. While the examples are in C++, the patterns themselves are still relevant to this day. In fact, there are now many books covering design patterns in specific languages, but the concepts are generally the same.

Aside from providing solutions to common software design problems, the benefit of using patterns is to create a common language and vocabulary that all programmers can use to help describe these problems. By providing a common vocabulary, anyone familiar with it will understand when someone says, for example, "this object implements the Adapter pattern to interface with the legacy database" or "you should use the Factory pattern to ensure future flexibility." The GoF book describes the Adapter pattern and Factory pattern in detail.

Obviously design patterns are a large topic and not something that I could do justice to in a single magazine article. I highly recommend you pickup (or borrow) a copy of the GoF book and read it. Even though it may be a little dated and does not apply directly to Objective-C, it will provide you with knowledge that will benefit you for years to come.

The Model-View-Controller Design Pattern

One common design pattern for developing GUI applications called the model-view-controller pattern or MVC pattern for short. The MVC pattern, while not described directly in the GoF book, is an old pattern with roots in Smalltalk from the early 1980s. It has proven such a successful pattern that it is prominent not only in modern Mac OS X applications in Cocoa, but also in Ruby on Rails web applications, and now in native iPhone applications, as just a few examples.

The MVC pattern breaks objects in an application into three roles: model objects, view objects, and controller objects. Objects in each role serve a particular function, and a single object should not perform multiple roles. The idea is to reduce dependencies, or coupling, between the components of an application. This loose coupling promotes reusability of each of the individual components.

Apple chose the MVC pattern as the basis for all Cocoa applications based on the success of the MVC pattern in Smalltalk and lessons learned in classic Mac OS. Apple used this experience to make programming for Mac OS X as easy as possible. They created the classes in AppKit and Foundation based on this collective experience, and these classes are now available for your use.

The Model

Model classes and objects are the core of your application. Think of them as your application, without a user interface. If, for example, you were developing an address book application, you would probably have objects to represent each contact, as well as objects to represent groups of contacts. Often, model objects are saved to disk and loaded in future invocations. Again, for an address book application, you would want to store all the contacts and groups on disk somewhere, so they could be loaded when your application next runs.

Ideally, model classes are completely independent of the user interface. This allows these classes to be reused in other applications and with other user interfaces. For example, you could use the same classes in a GUI, command line, and iPhone application. Or, you may be writing automated unit tests to ensure that the model objects work as desired. The reason these objects can be used in so many different situations is because they have no ties to the user interface. In technical terms, the model objects are not coupled to the user interface.

In our previous applications, the Rectangle class would be considered a model object. In fact, we have already reused this class in multiple applications. We started out using it in a command line application, and then used the exact same class when we started writing GUI applications.

The View

View objects and classes are at the other end of the spectrum. They represent the user interface and display information to the user. However, they are not responsible for storing the data they display. For GUI applications, we've already seen a number of view classes. For example, NSButton, NSTextField, and NSWindow are view classes. The NSApplication class is also considered part of the view as it represents the hub of a GUI application. Again, the main purpose of making generic view classes is to make them reusable in many applications. You could say that much of the AppKit framework is comprised of view classes, and the fact that AppKit provides so many pre-made view classes is one reason why it is easy to develop GUI applications for Mac OS X.

By designing AppKit using the MVC pattern, Mac OS X applications get to stand on the shoulders of giants. As programmers, we get to build on Apple's wealth of experience creating and designing GUI applications.

The Controller

Controller objects sit between the model and view classes and shuffles data back and forth. The GoF book describes a Mediator pattern where an object works like a real-world mediator communicating between two separate parties. The controller objects often follow this Mediator pattern.

One of the controller's responsibilities is to keep the model and view in sync. Figure 1 shows how the models, views, and controllers interact with each other. You can see the user interaction from the view goes through the controller. This user interaction is often in the form of targets and actions. For example, when a user clicks a button, the action method is on a controller class. The controller class is responsible for taking data out of the view and updating the model class. Conversely, if the model object changes without user interaction, it notifies the controller. It then updates the view accordingly. The controllers also generally act as the delegate and data source for views.


Figure 1: Model-View-Controller interaction

Hello World as MVC

Let's look at some of our programs through the MVC prism. The GUI from our original HelloWorld rectangle application is shown in Figure 2. The user interface is made up of standard Cocoa controls: a window, some text fields, and a button. These are all considered part of the view.


Figure 2: Rectangle application window

The rest of the application was implemented in two classes: HelloWorldController and Rectangle. As I mentioned above, the Rectangle class is considered a model class. The name I chose for HelloWorldController may not have made sense back then, as we didn't know about MVC, but it should be clear now. Since it performs the role of a controller class, I named it accordingly. Let's take a quick look at the interface for HelloWorldController in Listing 1.

Listing 1: HelloWorldController.h

#import <Cocoa/Cocoa.h>
@class Rectangle;
@interface HelloWorldController : NSObject
{
    IBOutlet NSTextField * _widthField;
    IBOutlet NSTextField * _heightField;
    IBOutlet NSTextField * _areaLabel;
    IBOutlet NSTextField * _perimiterLabel;
    
    Rectangle * _rectangle;
}
- (IBAction) calculate: (id) sender;
@end

This controller class has outlets to the text field, a calculate: action, and a _rectangle instance variable. Outlets and actions are generally how controllers and views are hooked up. Actions are used by views to notify the controller of a user's action. The controller uses outlets to get current values from the view and update the view to new vales of the model.

When the button is clicked and the action method is performed, the controller updates the _rectangle instance variable from the width and height text fields, and finally it updates the area and perimeter text fields:

- (void) updateAreaAndPerimeter
{
    [_areaLabel setFloatValue: _rectangle.area];
    [_perimiterLabel setFloatValue: _rectangle.perimeter];
}
- (IBAction) calculate: (id) sender
{
    _rectangle.width = [_widthField floatValue];
    _rectangle.height = [_heightField floatValue];
    [self updateAreaAndPerimeter];
}

You can see even in this simple example how the model view controller works. Data flows from the view to the model and vice versa through the controller. The controller receives a user action and updates both the model and the view to keep them in sync.

Model-View-Controller in Cocoa

You are highly encouraged to follow the MVC design pattern when writing your own applications. If you do, you will find that the Cocoa environment will help you get your job done faster. Apart from providing a rich set of view classes, there are some other benefits to following MVC. Some of the more advanced Cocoa technologies rely on MVC:

Document Architecture - Document-based applications follow the MVC pattern with your NSDocument subclass playing a controller role. When we changed our single window application to a document-based application that could save and open rectangle documents, we modified the Rectangle to implement the NSCoding protocol. By giving the Rectangle class the ability to convert itself to and from a sequence of bytes, it stays consistent with the role of a model class. However, it was the controller class that interacted with the view to perform the actual saving and loading to and from a file.

Cocoa Bindings - Bindings is a technique that allows you to remove a lot of repetitive code from of your controller classes. This is an advanced technique that in turn relies on key value coding (KVC) and key value observing (KVO). We will cover these topics in due time.

Core Data - Core Data allows you to easily create complex model objects and save them to disk. This allows you to remove a lot of repetitive code from your model classes. Again, we will cover Core Data in a future article.

Conclusion

The Model-View-Controller design pattern was identified as a way to design GUI applications that promotes loose coupling and reusability of its components. Apple chose the MVC pattern as the foundation for AppKit based on its previous success in Smalltalk. Because of this, you should design your Mac OS X applications with the MVC pattern in mind. It ensures your code is as reusable as possible, which is always a good thing, as you never know when you may need to use your model classes in another application. You will be glad you followed the MVC pattern when you do. As we will see in upcoming articles, Cocoa also rewards those following the MVC pattern.

Bibliography

Gamma, Erich; Richard Helm, Ralph Johnson, and John Vlissides. Design Patterns: Elements of Reusable Object-Oriented Software. 1995.


Dave Dribin has been writing professional software for over eleven years. After five years programming embedded C in the telecom industry and a brief stint riding the Internet bubble, he decided to venture out on his own. Since 2001, he has been providing independent consulting services, and in 2006, he founded Bit Maki, Inc. Find out more at http://www.bitmaki.com/ and http://www.dribin.org/dave".

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.