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".

 
AAPL
$102.99
Apple Inc.
+0.52
MSFT
$44.38
Microsoft Corpora
-0.50
GOOG
$532.71
Google Inc.
+6.17

MacTech Search:
Community Search:

Software Updates via MacUpdate

OmniOutliner 4.1.3 - Organize your ideas...
OmniOutliner is a flexible program for creating, collecting, and organizing information. Give your creativity a kick start by using an application that's actually designed to help you think. It's... Read more
BBEdit 11.0 - Powerful text and HTML edi...
BBEdit is the leading professional HTML and text editor for the Mac. Specifically crafted in response to the needs of Web authors and software developers, this award-winning product provides a... Read more
Apple Security Update 2014-005 - For OS...
Apple Security Update is recommended for all users and improves the security of Mac OS X. For information on the security content of this update, please visit this website: http://support.apple.com/... Read more
EyeTV 3.6.6 - Watch and record TV on you...
EyeTV brings a rich TV experience to your Mac. Watch live TV on your Mac. Pause, rewind, and record whenever you want. EyeTV gives you powerful control over what you watch and how you watch it. Put... Read more
RapidWeaver 6.0 - Create template-based...
RapidWeaver is a next-generation Web design application to help you easily create professional-looking Web sites in minutes. No knowledge of complex code is required, RapidWeaver will take care of... Read more
NTFS 12.0.39 - Provides full read and wr...
Paragon NTFS breaks down the barriers between Windows and OS X. Paragon NTFS effectively solves the communication problems between the Mac system and NTFS, providing full read and write access to... Read more
RestoreMeNot 2.0.3 - Disable window rest...
RestoreMeNot provides a simple way to disable the window restoration for individual applications so that you can fine-tune this behavior to suit your needs. Please note that RestoreMeNot is designed... Read more
Command-C 1.1.5 - Clipboard sharing tool...
Command-C is a revolutionary app which makes easy to share your clipboard between iOS and OS X using your local WiFi network, even if the app is not currently opened. Copy anything (text, pictures,... Read more
Macgo Blu-ray Player 2.10.9.1750 - Blu-r...
Macgo Mac Blu-ray Player can bring you the most unforgettable Blu-ray experience on your Mac. Overview Macgo Mac Blu-ray Player can satisfy just about every need you could possibly have in a Blu-ray... Read more
Apple iOS 8.1 - The latest version of Ap...
The latest version of iOS can be downloaded through iTunes. Apple iOS 8 comes with big updates to apps you use every day, like Messages and Photos. A whole new way to share content with your family.... Read more

Latest Forum Discussions

See All

TinType by Hipstamatic (Photography)
TinType by Hipstamatic 1.0 Device: iOS iPhone Category: Photography Price: $.99, Version: 1.0 (iTunes) Description: Create hauntingly beautiful, soul capturing portraits with TinType by Hipstamatic. Inspired by daguerreotypes,... | Read more »
The Latest Update for Heroes of Dragon A...
The Latest Update for Heroes of Dragon Age Introduces Daily PvE Challenges Posted by Ellis Spice on October 22nd, 2014 [ permalink ] | Read more »
A New Trailer has Been Revealed for Epic...
A New Trailer has Been Revealed for Epic of Kings Posted by Jessica Fisher on October 22nd, 2014 [ permalink ] Dead Mage Inc. has released a new, action-packed trailer for the upcoming Epic of Kings. | Read more »
Find the Line Review
Find the Line Review By Campbell Bird on October 22nd, 2014 Our Rating: :: INSLIDE THE LINESUniversal App - Designed for iPhone and iPad Tease out beautiful line drawings in this unique, free-to-play puzzle game.   | Read more »
The Silent Age Episode 2 Review
The Silent Age Episode 2 Review By Jennifer Allen on October 22nd, 2014 Our Rating: :: ROUNDING THINGS OFF NICELYUniversal App - Designed for iPhone and iPad Rounding off a great point and click adventure comes The Silent Age... | Read more »
Craft Your Own Mini-Games with Papercade
Craft Your Own Mini-Games with Papercade Posted by Jessica Fisher on October 22nd, 2014 [ permalink ] iPad Only App - Designed for the iPad Scrapbookers move over, Scrapgaming is the new thing. | Read more »
Reshape Review
Reshape Review By Jennifer Allen on October 22nd, 2014 Our Rating: :: SIMPLE SHAPESUniversal App - Designed for iPhone and iPad Match triangles together to form cubes in this fast-paced and twitchy game.   | Read more »
Miika (Games)
Miika 1.0.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.0 (iTunes) Description: Miika is a beautiful 3D puzzle game based on camera perspectives combined with the use of optical illusions. Miika challenges... | Read more »
Infuse Pro (Photography)
Infuse Pro 3.0 Device: iOS Universal Category: Photography Price: $9.99, Version: 3.0 (iTunes) Description: ** All-new version 3 includes fully licensed and certified DTS® and DTS-HD® audio! ** | Read more »
Swap Heroes (Games)
Swap Heroes 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: **Half price for a limited time only** Swap Heroes is a casual turn-based strategy adventure. Form a group of heroes and guide them... | Read more »

Price Scanner via MacPrices.net

Save with Best Buy’s College Student Deals
Take an additional $50 off all MacBooks and iMacs at Best Buy Online with their College Students Deals Savings, valid through November 1st. Anyone with a valid .EDU email address can take advantage... Read more
iPad Air 2 & iPad mini 3 Best Tablets Yet...
The new iPads turned out to be pretty much everything I’d been hoping for and more than I’d expected.”More” particularly in terms of a drinking-from-a-firehose choice of models and configurations,... Read more
Drafts 4 Reinvents iOS Productivity App
N Richland Hills, Texas based Agile Tortoise has announced the release of Drafts 4 for iPhone and iPad. Drafts is a quick capture note taking app with flexible output actions. Drafts 4 scales from... Read more
AT&T accepting preorders for new iPads fo...
AT&T Wireless is accepting preorders for the new iPad Air 2 and iPad mini 3, cellular models, for $100 off MSRP with a 2-year service agreement: - 16GB iPad Air 2 WiFi + Cellular: $529.99 - 64GB... Read more
Apple offering refurbished Mac Pros for up to...
The Apple Store is offering Apple Certified Refurbished 2013 Mac Pros for up to $600 off the cost of new models. An Apple one-year warranty is included with each Mac Pro, and shipping is free. The... Read more
Select MacBook Airs $100 off MSRP, free shipp...
B&H Photo has 2014 a couple of MacBook Airs on sale for $100 off MSRP. Shipping is free, and B&H charges NY sales tax only. They also include free copies of Parallels Desktop and LoJack for... Read more
13-inch 2.5GHz MacBook Pro on sale for $100 o...
B&H Photo has the 13″ 2.5GHz MacBook Pro on sale for $999.99 including free shipping plus NY sales tax only. Their price is $100 off MSRP. Read more
Strong iPhone, Mac And App Store Sales Drive...
Apple on Monday announced financial results for its fiscal 2014 fourth quarter ended September 27, 2014. The Company posted quarterly revenue of $42.1 billion and quarterly net profit of $8.5 billion... Read more
Apple Posts How-To For OS X Recovery
OS X 10.7 Lion and later include OS X Recovery. This feature includes all of the tools you need to reinstall OS X, repair your disk, and even restore from a Time Machine backup. OS X Recovery... Read more
Mac OS X Versions (Builds) Supported By Vario...
Apple Support has posted a handy resource explaining which Mac OS X versions (builds) originally shipped with or are available for your computer via retail discs, downloads, or Software Update. Apple... Read more

Jobs Board

Senior Event Manager, *Apple* Retail Market...
…This senior level position is responsible for leading and imagining the Apple Retail Team's global event strategy. Delivering an overarching brand story; in-store, Read more
*Apple* Solutions Consultant (ASC) - Apple (...
**Job Summary** The ASC is an Apple employee who serves as an Apple brand ambassador and influencer in a Reseller's store. The ASC's role is to grow Apple Read more
Project Manager / Business Analyst, WW *Appl...
…a senior project manager / business analyst to work within our Worldwide Apple Fulfillment Operations and the Business Process Re-engineering team. This role will work Read more
*Apple* Retail - Multiple Positions (US) - A...
Job Description: Sales Specialist - Retail Customer Service and Sales Transform Apple Store visitors into loyal Apple customers. When customers enter the store, Read more
Position Opening at *Apple* - Apple (United...
…customers purchase our products, you're the one who helps them get more out of their new Apple technology. Your day in the Apple Store is filled with a range of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.