Message Design Patterns in Cocoa Touch
Message Design Patterns in Cocoa Touch
Caio Lima
September 2012
1
TABLE OF CONTENTS
EXECUTIVE SUMMARY...............................................................................................................3
1.0 INTRODUCTION.....................................................................................................................4
2.0 ANALYSIS................................................................................................................................5
2.1 Delegation.......................................................................................................................5
2.1.1 Method............................................................................................................5
2.1.2 Advantages of Using Delegates.........................................................................6
2.1.3 Disadvantages of Using Delegates.....................................................................7
2.2 Notifications....................................................................................................................7
2.2.1 Method............................................................................................................7
2.2.2 Advantages of Using Notifications.....................................................................8
2.2.3 Disadvantages of Using Notifications.................................................................8
2.3 Target-Action..................................................................................................................8
2.3.1 Method............................................................................................................9
2.3.2 Advantages of Using Target-Action..................................................................9
2.3.3 Disadvantages of Using Target-Action............................................................10
3.0 CONCLUSIONS....................................................................................................................10
REFERENCES..............................................................................................................................11
2
EXECUTIVE SUMMARY
This report analyzes advantages and disadvantages of sending messages to objects using delegation,
notifications and the target-action patterns.
The delegation pattern pairs a very general object to another object known as the delegate which
receives messages from this general object. Advantages include its simplicity, it decouples classes from
one another and reduces the need to subclass. The main disadvantage is that it requires significantly
more time to implement.
The notifications pattern is based off of a dispatcher that relays predetermined messages for any
registered object to observe. Advantages of this method are that it can simultaneously send a message
to many objects at once, message observers and senders are completely decoupled, and any object can
send a notification. Disadvantages are that developers need to foresee the use of notifications and that
notifications are sent regardless if they have observers or not.
The target-action pattern is used for connecting controls with objects and allows user events to be
mapped to an instruction for the program. Advantages for this pattern are that it prevents the need for
writing event handlers, reduces the need for subclassing, and works well for user interfaces.
This report finds that delegation is best suited for one-to-one communication, notifications are useful for
one-to-many communication, and target-action is best for messaging a user interface.
3
1.0 INTRODUCTION
In recent years, the utility of the mobile phone has continued to evolve. With the introduction of mobile
applications, consumers are rapidly turning to their handsets for purposes beyond communication. In the
increasingly popular smartphone market, Apples iPhone has been a well sought-after device for many
developers to showcase their applications and share their ideas on the iOS system. These applications
can range from games to utilities or even social networking apps among many other categories. Apple
has developed a native object-oriented Application Programming Interface (API) known as Cocoa for
their Mac OS X operating system and Cocoa Touch for the iOS as a base framework for developing
these apps.
When developing for Mac OS X and iOS, Apple highly encourages developers to follow the
object-oriented programming paradigm in order to properly use the Cocoa API. This paradigm
promotes the use of objects, usually instances of a class, working together to solve problems by
sending messages to each other. Three patterns of passing messages between objects include
delegation, notifications, and target-action.
These messaging design patterns are presented and analyzed, discussing their advantages and
disadvantages, primarily focusing on experiences with the Cocoa Touch API, but the principles and
findings can easily be transferred to the Cocoa API and other object-oriented frameworks. This report
is intended for readers with some previous programming experience and some familiarity with the
Cocoa Touch API.
4
2.0 ANALYSIS
This section introduces three messaging design patterns and analyzes their advantages and
disadvantages to compare how these methods fare in different situations and how they abide to major
object-oriented programming principles. Messages are sent between objects in order for them to
communicate with each other and to be able to coordinate the completion of certain tasks. Recent
developing experiences of the Paperless Post Mobile Team are used to evaluate these criteria and
analyze the opportunities within each method.
2.1 Delegates
Delegation is used very frequently in Cocoa Touch. As Apple states, Delegation is a simple and
powerful pattern in which one object in a program acts on behalf of, or in coordination with, another
object (Apple, Cocoa Core Competencies - Delegation, 2012). This allows objects to delegate tasks
to other objects which may be more suitable for accomplishing said tasks.
2.1.1 Method
The principle behind the delegation pattern is that two objects can work together to solve a problem.
One object is a very general object that is meant to be reusable in a multitude of different scenarios. This
object maintains a reference to another object, known as its delegate, which receives messages sent at
key times sent by the general object. A common series of sent messages are to inform the delegate of
different events that occur throughout a task and give the delegate a chance to do extra tasks in between
these events. For example, the UIViewController class provides a fundamental view management model
for iOS apps. When displaying its main view, there are a series of events a UIViewController goes
5
through to get the view onto the screen. The view is first created by the -loadView method and once the
view controller finishes loading the view into memory, it sends the -viewDidLoad message to the
delegate as a method so it can customize the view immediately after it loads. When the view controller is
about to release the view from memory, it sends -viewWillUnload to alert the delegate and
-viewDidUnload once it has finished unloading the view so the delegate has the opportunity to perform
more tasks at that time such as unloading other objects related to that view.
2.1.2 Advantages of Using Delegates
Delegation is a very simple and flexible pattern. One of its major advantages is that it substantially
decreases the need to subclass Cocoa objects to implement application-specific behaviour. Several of
the more intricate classes such as NSApplication, NSBrowser, NSTableView, NSText, and
NSWindow are rarely if ever subclassed because the delegation pattern provides a better alternative
(Buck/Yacktman, 2009). Further, due to the reduction of the amount of subclassing, another positive
consequence is that using delegates greatly reduces coupling between objects, which helps it abide to
the object-oriented programming model. The coupling between an object and its delegate is so loose
that the object can function without any delegate at all, and a delegate is free to implement any subset of
the potential delegate methods (Buck/Yacktman, 2009). This looseness allows objects to be reused
with much ease.
6
2.1.3 Disadvantages of Using Delegates
Though there are advantages to this method, it does come with its downfalls. The biggest of these
downfalls is that it requires to be carefully designed in order to be effective. If there is no delegate
support and the delegate messages are not sent in the right situations, developers may be inclined to
subclass in order to implement any application-specific behaviour properly. This would increase
coupling between objects and results in less reusable code.
2.2 Notifications
The notifications pattern, also known as the observer pattern, is also widely used throughout the
Cocoa Touch framework. It enables communication between objects without tight coupling
(Buck/Yacktman, 2009), and is rather flexible in many situations.
2.2.1 Method
In Cocoa, the notifications pattern usually involves the use of a central hub called NSNotificationCenter
for distributing instances of the NSNotification class to registered observers. As a comparison, the
interaction of the notification center with the observers resembles that of a newspaper deliverer. An
object sends a notification to the NSNotificationCenter, and the center sends it to each of its observers
just as the newspaper deliverer distributes newspapers to each subscriber. One place where
notifications are commonly used in Cocoa Touch are during database changes. When a value in a
database changes, it is quite likely that many objects are interested in the change so they can update
themselves to the most recent values or adjust accordingly.
7
2.2.2 Advantages of Using Notifications
As with using delegates, using notifications nicely decouples two objects. The sender and the receiver of
the notifications do not even need to know of each others existence for this pattern to work well, which
prevents unwanted dependencies and allows for more a reusable and maintainable project. One nice
feature it has over delegation is that a message can be sent as a notification to as many observers as
desired whereas delegation allows for only one delegate. Another upside is that any object can post a
notification, which enables easy communication with all the observers in different parts of the program or
application.
2.2.3 Disadvantages of Using Notifications
Similar to using delegates, a notable weakness of the notifications pattern is that developers need to
anticipate the need for notifications. The notifications have to be designed in a way that there are objects
that will find them useful, but should be aware that posting too many notifications can make them less
practical. Like the newspaper deliverer, if the printing company always outputs newspapers but there is
nobody subscribed, the papers are discarded and resources are wasted. If there is no need for the
notifications, they will use unneeded processing power, sacrifice efficiency and could even lock up the
user interface.
2.3 Target-Action
Even though delegation and notifications are good ways to communicate between objects, they are not
always practical to implement. When building a graphical user interface, a developer needs a way to
arrange control elements such as slide bars, buttons and checkboxes, and connect them to
8
application-specific operations in order to be able to display information and allow interaction. For
example, an application interface could provide a button whose function is to alternate the background
colour of the screen from red to blue. Target-action is a commonly used method to provide the
connection between the act of pressing the button and changing the colour of the background.
2.3.1 Method
On a high level, Cocoa uses the target-action pattern to provide a translation layer between a control
element and another object. A control element in a user interface has a simple role: it interprets the
intent of the user and instructs some other object to carry out that request (Apple, target-action
Mechanism, 2010). For example, the object receiving the instruction from a button control is known as
the target, usually the UIViewController managing the button, and the action is the message sent by the
control to the target. Suppose the action is to change the screen from red to blue, then once the button
is pressed, it will send the UIViewController an instruction telling it to change the screen to blue. This
action is now triggered every time the button is pressed.
2.3.2 Advantages of Using Target-Action
The target-action pattern works superbly for controlling user interfaces. This dynamic messaging method
reduces the need for manual event handling systems common in other frameworks (Buck/Yachtman,
2009), drastically reducing implementation time and facilitating the creation of an interactive user
interface. This flexibility satisfies the user interface needs for most applications and prevents the need for
subclassing, which results in less coupling and easier code to maintain.
9
2.3.3 Disadvantages of Using Target-Action
This messaging pattern works well for providing a means of communication between a control and
another object, however, it is quite limited to that scope. The biggest disadvantage is that though it is
possible to use this method between any object, it is designed primarily for use with controls and user
interfaces. Another downside to this pattern is that the messages are only sent one way from the object
to the target. This means that the sender does not know if the target is capable of receiving the given
instructions and requires some careful planning in advance to ensure the application does not crash.
Also, since target-action treats messages as if they were objects in a sense, it is not practical to send
more than one or two messages to a target for a given event, reducing the amount of situations that this
pattern can be applied to.
3.0 CONCLUSIONS
There are various ways to send messages between objects in the Cocoa framework. Some methods
can be better than others in different situations.
All three design patterns reduce the need for subclassing and help decouple objects.
The delegation pattern works best for one-to-one communication.
The notification pattern works best for one-to-many communication.
The target-action pattern excels at relaying messages for user interfaces and is fastest to implement.
10
REFERENCES
Apple Inc. (2010), Target-Action Mechanism.
Retrieved September 15, 2012
from
http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/CocoaFundamentals/Commu
nicatingWithObjects/CommunicateWithObjects.html
Apple Inc. (2009), Notification Programming Topics.
Retrieved September 15, 2012
from
http://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Notifications/Articles/Notifica
tions.html#//apple_ref/doc/uid/20000215-74147
Erik M. Buck & Donald A. Yachtman (2009), Cocoa Design Patterns.
Published 2010 by Pearson Education, Inc.
11