Design Patterns available in Cocoa Touch framework

Firstly What is Design Pattern?

Design patterns are reusable solutions to common problems in software design. They’re templates designed to help you write code that’s easy to understand and reuse. They also help you create loosely coupled code so that you can change or replace components in your code without too much of a hassle.

OOPS -> Object-oriented programming was developed to make code more maintainable, reusable, extensible, and understandable by encapsulating all the functionality behind well-defined interfaces. The actual details of how something works (as well as its data) are hidden, which makes modifying and extending an application much easier.

Here you will come to know:

  • What the design pattern is.
  • Why you should use it.
  • How to use it and, where appropriate, common pitfalls to watch for when using the pattern.

Most common Cocoa Design Patterns:

  • Creational: Singleton and Abstract Factory.  ——–>>> CSA (Creational, Singleton, Abstract)
  • Structural: MVC, Decorator, Adapter, Facade and Composite. ——–> SMDAFC
  • Behavioural: Observer, Memento, Chain of Responsibility and Command. ——–> BOMCrc


 It classifies objects according to their general role in your application and encourages clean separation of code based on role.


basics of iOS mobile app development

The three roles are:

  • Model: The object that holds your application data and defines how to manipulate it. For example, in your application the Model is your Album class.

.h file

#import <Foundation/Foundation.h>

@interface Album : NSObject

@property (nonatomic, copy, readonly) NSString *title, *artist, *genre, *coverUrl, *year;

//readonly because there is no need to change them after the Album object is created.

-(id)initWithTitle:(NSString*)title artist:(NSString*)artist genre:(NSString*)genre coverUrl:(NSString*)coverUrl year:(NSString*)year;

// The above method is object initializer. When you create a new Album, you will pass album title, artist, genre, coverUrl, year.


.m file

#import “Album.h”

@implementation Album

//init method to create new Album instances

-(id)initWithTitle:(NSString *)title artist:(NSString *)artist genre:(NSString *)genre coverUrl:(NSString *)coverUrl year:(NSString *)year {

    self = [super self];

    if (self) {

        _title = title;

        _artist = artist;

        _genre = genre;

        _coverUrl = coverUrl;

        _year = year;


    return self;



  • View: The objects that are in charge of the visual representation of the Model, where the user can interact with; basically, all the UIViews and their subclasses. In your application the View is represented by your AlbumView class.

.h file

#import <UIKit/UIKit.h>

@interface AlbumView : UIView

-(id)initWithFrame:(CGRect)frame albumCover:(NSString*)albumCover;


.m file

#import “AlbumView.h”

@implementation AlbumView{

    // these are private variables. These are declared here not in interface file because no class outside AlbumView class needs to know of the existence of these variables since they are used only in the implementation of the class internal functionlity.

    UIImageView *coverImage;

    UIActivityIndicatorView *indicator;


// implementation of the initializer

-(id)initWithFrame:(CGRect)frame albumCover:(NSString *)albumCover {

    self = [super initWithFrame:frame];

    if (self) {

        self.backgroundColor = [UIColor blackColor];

        coverImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 5, frame.size.width10, frame.size.height10)];

        [self addSubview:coverImage];

        indicator = [[UIActivityIndicatorView alloc] init]; =;

        indicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;

        [indicator startAnimating];

        [self addSubview:indicator];


    return self;



  • Controller: The controller is the mediator that coordinates all the work. It accesses the data from the model and displays it with the views, listens to events and manipulates the data as necessary. Can you guess which class is your controller? That’s right: ViewController.

.h file

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


.m file

#import “ViewController.h”

@interface ViewController ()


@implementation ViewController

– (void)viewDidLoad


    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.


– (void)didReceiveMemoryWarning


    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.



Figure explanation:


 The View can notify the Controller of actions the user performed and the Controller will either update the Model if necessary or retrieve any requested data.

                        On the other side the Model notifies the Controller of any data changes, and in turn, the Controller updates the data in the Views.

MVC helps in code separation and reusability. Ideally, the View should be completely separated from the Model. If the View doesn’t rely on a specific implementation of the Model, then it can be reused with a different model to present some other data.   

               For example, if in the future you’d also like to add movies or books (apart from Album) to your project, you could still use the same AlbumView to display your movie and book objects.  Furthermore, if you want to create a new file in your project that has something to do with Album, you could simply reuse your Album class, because it’s not dependent on any view. That’s the strength of MVC!

How to Use the MVC Pattern

  1. First, you need to ensure that each class in your project is either a Controller, a Model or a View; don’t combine the functionality of two roles in one class.We did great by creating an Album class(Model), an AlbumView class(View) and a ViewController class(Controller).
  2. Second, in order to ensure that you conform to this method of work you should create three project groups to hold your code, one for each category.mvc2

The iOS frameworks are object oriented. An easy way to understand what that really means is to think about a team working in an office. The work that needs to get done is divided up and assigned to individual team members (in this case, objects). Each team member has a job and works with other team members to get things done.

What’s more, a good team member doesn’t care how other members do their work, just that they do it according to the agreed upon division of labor. Likewise, an object in object-oriented programming takes care of its own business and doesn’t care what the object in the virtual cubicle next door is doing, as long as it will do what it’s supposed to do when asked to do it.

Now the Question arises Exactly how do you decide on the objects and what each one does?

Sometimes the answer to that question is pretty easy — just use the real world as a model. In a RoadTrip app, for example, some of the classes of model objects are Trip, Events, Destination, and so on. But when it comes to a generic program structure, how do you decide what the objects should be? So comes the MVC – The King of Design patterns

The MVC pattern is a well-established way to group application functions into objects.The MVC is a high-level pattern — it addresses the architecture of an application and classifies objects according to the general roles they play in an application, rather than drilling down into specifics.

  • Model objects: These objects together comprise the content of your app. They contain the app’s data and logic.

    You can think of the model (which may be one object or several that interact), doesn’t give a hoot about what where it is used up.

    Even though it owns its data, it should have no connection to the user interface and should be blissfully ignorant about what’s done with its data.

  • View objects: These objects display things on the screen and respond to user actions. Pretty much anything you can see is a kind of view object — the window and all the controls, for example.

    Your views know how to display information they receive from the model object and how to get any input from the user the model may need. But the view itself should know nothing about the model. It may handle a request to display some events, but it doesn’t bother itself with what that request means.

    You can think of the view as a television screen that doesn’t care about what program it’s showing or what channel you just selected.

    The UIKit framework provides many different kinds of views.

    If the view knows nothing about the model, and the model knows nothing about the view, how do you get data and other notifications to pass from one to the other? To get that conversation started (Model: “I’ve just updated my data.” View: “Hey, give me something to display,” for example), you need the third element in the MVC i.e the Controller.

  • Controller objects: Controller objects connect the application’s view objects to its model objects. They supply the view objects with what they need to display (getting it from the model) and also provide the model with user input from the view.

In Objective-C, classes include instance variables, properties, and methods (that can access the instance variables of a class). Classes are about files in your project that contain code. Classes are types in your program.

Objects, on the other hand, exist at runtime and are instances of a class. You can think of a class as a blueprint to build an object of that type.

MODEL is reusable of all in MVC.

How View and Controller communicate with each other ->With IBOUTLET and IBACTION, properties and method are connected to a Controller in the View.


The Singleton design pattern ensures a class only has one instance, and provides a global point of access to it. The class keeps track of its sole instance and ensures that no other instance can be created. Singleton classes are appropriate for situations where it makes sense for a single object to provide access to a global resource, such as with classes that offer some general service or resource.

A singleton class also prevents callers from copying, retaining, or releasing the instance.


// Your dealloc method will never be called, as the singleton survives for
 the duration of your app.
    // I'm never called!
    [super dealloc];
Singleton class

You obtain the global instance from a singleton class through a factory method. It usually uses lazy loading to create the single instance when it’s needed the first time.

ex: if you have a class that provides sounds to other objects in an application, you might make it a singleton.

ex: For example:Apple uses these Singleton class like  [NSUserDefaults standardUserDefaults], [UIApplication sharedApplication], [UIScreen mainScreen], [NSFileManager defaultManager] all return a Singleton object.

You’re likely wondering why you care if there’s more than one instance of a class floating around. Code and memory is cheap, right?

You can create multiple instance of a class. But if it is not needed, then we should use Singleton Class. By this way it will be thread safe to access a single resource file, than to have many class modifying the configuration file possibly at the same time.

How to Use the Singleton Pattern

.h file

@interface LibraryAPI : NSObject
+ (LibraryAPI*)sharedInstance;

.m file

+ (LibraryAPI*)sharedInstance
    // 1
    static LibraryAPI *_sharedInstance = nil;
    // 2
    static dispatch_once_t oncePredicate;
    // 3
    dispatch_once(&oncePredicate, ^{
        _sharedInstance = [[LibraryAPI alloc] init];
    return _sharedInstance;


  1. Declare a static variable to hold the instance of your class, ensuring it’s available globally inside your class.
  2. Declare the static variable dispatch_once_t which ensures that the initialization code executes only once.
  3. Use Grand Central Dispatch (GCD) to execute a block which initializes an instance of LibraryAPI. This is the essence of the Singleton design pattern: the initializer is never called again once the class has been instantiated.

So the first time a client sends the sharedInstance message, the property instance isn’t yet initialized, so you create a new instance of the class and return a reference to it.

The next time you call sharedInstance, instance is immediately returned without any initialization because the code inside the dispatch_once block won’t be executed (since it’s already executed once) and you receive a reference to the previously created instance of LibraryAPI. This logic promises that only one instance exists at all times.

other way of implementing Singleton class without GCD and Blocks (better way is using GCG and Blocks as this is thread safe)

.m file

+ (LibraryAPI*)sharedInstance
    static LibraryAPI *_sharedInstance = nil;
    if(_sharedInstance == nil) {
         _sharedInstance = [[LibraryAPI alloc] init];
 return _sharedInstance;


+ (LibraryAPI *)sharedInstance


  static LibraryAPI _sharedInstance = nil;

@synchronized(self) {

      if (_sharedInstance == nil)

               _sharedInstance = [[LibraryAPI alloc] init];


return _sharedInstance;


Test Code

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
 // Insert code here to initialize your application
LibraryAPI *singleton1 = [[LibraryAPI alloc] init]; 
NSLog(@"singleton1 %@",singleton1); //Will print null 

LibraryAPI *singleton2 = [LibraryAPI sharedInstance];
NSLog(@"singleton2 %@",singleton2);

LibraryAPI *singleton3 = [LibraryAPI sharedInstance]; 
NSLog(@"singleton3 %@",singleton3); 

2015-03-10 23:02:56.401 SingletonDesignPattern[28050:896228] 
singleton1 (null) 
2015-03-10 23:02:56.401 SingletonDesignPattern[28050:896228] 
singleton2 0x618000001a80>
 2015-03-10 23:02:56.401 SingletonDesignPattern[28050:896228] 
singleton3 0x618000001a80>

Singleton in Swift

To implement the singleton pattern in Swift, we make use of class constants, which were introduced in Swift 1.2. If you are having issues with the below code snippet, then make sure that you are using Xcode 6.3+.

Let me walk you through the short implementation of the Logger class. We start by declaring a class named Logger. To implement the singleton pattern, we declare a type property, sharedInstance, of type Logger.

By using the static keyword, the sharedInstance constant is tied to the Logger class instead of instances of the class. The sharedInstance constant is referred to as a type property since it is tied to the type, that is, the Loggerclass. We access the singleton object through the Logger class.

You may be wondering why we don’t use the dispatch_once function like we did in the Objective-C implementation. Under the hood, Swift already uses dispatch_once when initializing static constants. That’s something you get for free in Swift.

Abstract Factory

The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes. The client is decoupled from any of the specifics of the concrete object obtained from the factory.


The Adapter design pattern converts the interface of a class into another interface that clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces. It decouples the client from the class of the targeted object.

Chain of Responsibility

The Chain of Responsibility design pattern decouples the sender of a request from its receiver by giving more than one object a chance to handle the request. The pattern chains the receiving objects together and passes the request along the chain until an object handles it. Each object in the chain either handles the request or passes it to the next object in the chain.


The Command design pattern encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations. The request object binds together one or more actions on a specific receiver. The Command pattern separates an object making a request from the objects that receive and execute that request.


The Composite design pattern composes related objects into tree structures to represent part-whole hierarchies. The pattern lets clients treat individual objects and compositions of objects uniformly. The Composite pattern is part of the Model-View-Controller aggregate pattern.


The Decorator design pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality. As does subclassing, adaptation of the Decorator pattern allows you to incorporate new behavior without modifying existing code. Decorators wrap an object of the class whose behavior they extend. They implement the same interface as the object they wrap and add their own behavior either before or after delegating a task to the wrapped object. The Decorator pattern expresses the design principle that classes should be open to extension but closed to modification.


The Facade design pattern provides a unified interface to a set of interfaces in a subsystem. The pattern defines a higher-level interface that makes the subsystem easier to use by reducing complexity and hiding the communication and dependencies between subsystems.


The Iterator design pattern provides a way to access the elements of an aggregate object (that is, a collection) sequentially without exposing its underlying representation. The Iterator pattern transfers the responsibility for accessing and traversing the elements of a collection from the collection itself to an iterator object. The Iterator defines an interface for accessing collection elements and keeps track of the current element. Different iterators can carry out different traversal policies.


The Mediator design pattern defines an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently. These objects can thus remain more reusable. A “mediator object” in this pattern centralizes complex communication and control logic between objects in a system. These objects tell the mediator object when their state changes and, in turn, respond to requests from the mediator object.


The Memento pattern captures and externalizes an object’s internal state—without violating encapsulation—so that the object can be restored to this state later. The Memento pattern keeps the important state of a key object external from that object to maintain cohesion.


1.The Observer design pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. Or more specifically, if an object’s property changes in one instance, another object can react to it.

2.The Observer pattern is essentially a publish-and-subscribe model in which the subject and its observers are loosely coupled.

3.Communication can take place between the observing and observed objects without either needing to know much about the other – thus encouraging a decoupled design. This pattern’s most often used to notify interested objects when a property has changed.

4.The usual implementation requires that an observer registers interest in the state of another object. When the state changes, all the observing objects are notified of the change. Apple’s Push Notification service is a global example of this.

If you want to stick to the MVC concept (hint: you do), you need to allow Model objects to communicate with View objects, but without direct references between them. And that’s where the Observer pattern comes in.

Cocoa and Cocoa Touch development implements the observer pattern in two familiar ways: Notifications and Key-Value Observing (KVO).

Notifications -> 

Key-Value Observing (KVO) -> Think of all those times when you write a protocol, or create an NSNotification to tell another class to do something. Both those approaches are valid, and sometimes necessary, but there is a simpler alternative i.e KVO.

In KVO, an object can ask to be notified of any changes to a specific property; either its own or that of another object.

Ex: Imagine that you have a Tabbed Application template in Xcode. You have two view controllers, and imagine there’s a text field in the first view controller. Someone enters text, and you’d like the same text to appear in the second view controller.

First View Controller

The ingredients we need in the first view controller are:

  • a reference to the second view controller, hence we need to import its header file.
  • a UITextField property
  • an NSString property to hold our “message” that we want the second view controller to react to

We’ll also conform to the text field protocol so we can dismiss the keyboard appropriately:

#import "FirstViewController.h"
#import "SecondViewController.h"

@interface FirstViewController () 
@property (strong, nonatomic) IBOutlet UITextField *textField;
@property (nonatomic, strong) NSString *theMessage;

Registering an Observer

The first view controller needs to register an observer for the second view controller, and tell it which property (or key-value pair) should be observed. It’s a message that’s sent under the hood if our property changes.

In viewDidLoad, we’ll grab a reference to the second view controller and do just that:

- (void)viewDidLoad {
    [super viewDidLoad];
    // grab a reference to the second view controller
    SecondViewController *second = self.tabBarController.viewControllers.lastObject;
    [self addObserver:second forKeyPath:@"theMessage" options:
          NSKeyValueObservingOptionNew context:nil];

How you get the reference to your other object (i.e your observer who is observing your change) is dependent on your own app’s design of course. In the case of Apple’s Tabbed Application template, we can reach up to the navigation controller and grab the last object (i.e. the second view controller).

Notice the options parameter in this method: we can either pass the new (updated) value of our property (NSKeyValueObservingOptionNew), or we can see what the value was before it was changed (NSKeyValueObservingOptionOld). There are times where we may need that, but not today.

The keyPath parameter is equivalent to the property in our first view controller.

All that remains to be done here is to read out the text field and change our property with its contents. We’re implementing the UITextFieldDelegate protocol, so as soon as the return key is pressed on the keyboard, we can react and read the value:

- (BOOL)textFieldShouldReturn😦UITextField *)textField {
    // read out the text field
    self.theMessage = textField.text;
    // and dismiss the keyboard
    [textField resignFirstResponder];
    return YES;

Second View Controller

The implementation for the second view controller’s reaction is even easier: all we have to do is implement a single method, which will be called when the first view controller’s property changes:

- (void)observeValueForKeyPath😦NSString *)keyPath ofObject😦id)object 
   change😦NSDictionary *)change context😦void *)context {
    // retrieve the first view controller's message
    NSString *message = [(NSString *)object valueForKey:@"theMessage"];
    NSLog(@"The message was %@", message);

That is it. Second view controller is notified and this method is called. It’s like magic!

You also need to unregister as an observer when you’re done.

[observername removeObserver:self forKeyPath:@"theMessage"];


Try more KVO next time when you need to send some data from one object to another.


The Proxy design pattern provides a surrogate, or placeholder, for another object in order to control access to that other object. You use this pattern to create a representative, or proxy, object that controls access to another object, which may be remote, expensive to create, or in need of securing. This pattern is structurally similar to the Decorator pattern but it serves a different purpose; Decorator adds behavior to an object whereas Proxy controls access to an object.


The Receptionist design pattern addresses the general problem of redirecting an event occurring in one execution context of an application to another execution context for handling. It is a hybrid pattern. Although it doesn’t appear in the “Gang of Four” book, it combines elements of the Command, Memo, and Proxy design patterns described in that book. It is also a variant of the Trampoline pattern (which also doesn’t appear in the book); in this pattern, an event initially is received by a trampoline object, so-called because it immediately bounces, or redirects, the event to a target object for handling.

Template Method

The Template Method design pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. The Template Method pattern lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s