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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.