Skip to main content

Design Pattern in iOS

Target/Action:


Design pattern known for handling to controls (UIButton, UITextField etc) events.

Target

Action

In the above diagram UIViewController (target) is responsible for action of UIButton (control). This design pattern enables to write the custom logic of controls in any object (UIViewController) without sub classing the control (UIButton) object. So if you connect a button to an outlet in storyboard it depicts the target/action paradigm. The action is defined by the name of a selector. The target can either be a concrete object or it can be NULL

We can take the example of this pattern as if we press (Action) a electricity switch then target (Fan) will start rotating.

Code :

In programming we are using this pattern when we use the following method for any controls:
addTarget:action:forControlEvents:

When we add any action through xib or storyboard then also we are using action target design pattern. So any IBAction we used in iOS is an example of target /Action design pattern.
- (IBAction)doSomething:(id)sender;

Detail:

Composite:

It is representation of group of object as a single object.  In this design pattern an object strongly hold the other objects and represent as single object.


One of the most common examples of composite design pattern is View hierarchy. Following is an example in which UiView contain the UIButton and UITextfield object.



Code:

A composite pattern example in our code can be following.
Lets say we are creating an application of To-do list. In our to-do list view we have several other view objects?

1) UITable
2) UIButton


So it totally depends upon your requirement and in this example. I consider table view to show a list of to do task and UIButton to create a new To-do.

So our To-do view has interface similar to following
@interface ToDoView{
UITableView     *toDoListView; // Composite Example
UIButton            *newToDoButton; // Composite Example
}

Detail:


Responder Chain:

This design pattern is responsible for delivering the touch events to hit view.
In responder chain like the name says we have chain of object connected to each other. Any event or task which is not handle by any object pass to the next object in chain until the end or the object which can handle the task.

So how it is used in iOS Touch event handling? 

First UIApplication pick the event from the event queue and deliver it to the key window object. Then key window decide which object has to receive the event based on the touch position. Window checks it by hit test method. If the receiving object not handling the event then it pass to the next responder in a chain and continuos until reach to the object handling it or the window object again.



Detail:


Delegate:

Initially I thought protocol are only use to implement delegate pattern or I protocol or delegate are similar term :). But then I realize that I was wrong. Delegate is design pattern, which enable us to write a custom behavior without sub class the class


So when we need to customize the application behavior at application launch time or at foreground we need UIApplication object but iOS provide that feature by app delegate. By using app delegate we can customize the app lunch behavior without sub class the UIApplication object.


Implementation:

So if we want to implement this design pattern for our classes then we need to declare a suitable protocol. Which contain the signature of the methods which other object require customizing the behavior of the object. So lets take an example when we declare an HTTP Connection class in our application we need that every other object can customize the behavior on when connection finish with the loading of data. So in our HTTP Connection protocol we need a method, which allow the other object to customize the behavior on finish loading. The signature can be following:

- (void) connection:(HTTPConnection)con didFinishLoadingWithData:(NSData*)data;

So rest you can think which method we require and what will be the signature?
Do we need to expose an error method?
Do we need to expose did response method?


So in above example we are customizing the behavior of HTTP Connection object.


DataSource:

It is very much similar to delegate design pattern. The basic idea is customizing the data retrieval without sub classing. So let put a question if table view does not have data source methods than what other trick we will like to add to provide that to table view.

1) Sub classing? (We need much detail of UITableview call like which method to override and on which method we need to call super)

So data source provide an elegant way to provide customizing data to the object.

                                                            




Implementation:



It is the same as delegate design pattern. So we need to design a protocol, which can provide your object the required data.
                                     

MVC (Modal-View-Controller) :

So now we come to an Architectural pattern for the UI application. We all have own definition of MVC and we all know about the most common design pattern. 

MVC is the pattern to provide organization structure to your application based on the responsibilities.

M - Modal that is responsible of maintaining the data.
V - View that is responsible for display the data to user.
C - Controller It handle the interaction between the modal and view.

In iOS there are two types of controller:

Coordinating (Containment) Controller: It mainly manages the functioning of an entire application.  So it mainly contains the objects, which have life cycle of application level. We mostly use UINaviagtion Controller as co-ordinating controller. After iOS5 you can declare your own coordinate controller.


UIViewController : UIKIt provide us in built UIView Controller to manage all the view related event.


Detail:


Applying Pattern:

Let us take a simple example of message application in which user can share a message and all the shared message shown in a list with the user pic.

So first thought for MVC what will your model look like: 

Modal
1) User -
      a) Picture
      b) Message

View
 1) Shared Message View
            i) Table View (Show all the messages from all the users)
            ii) NavBar
            iii) UIBarButton (New)
  2) New Message View
            i) Text View
            ii) NavBar
            iii) UIBarButton (Done)
            iv) UIBarButton (Back)

Controller
1) Shared Message View Controller
            i) Table View Datasource (DataSource Design Pattern)
            ii) Table View Delegate (Delegate Design Pattern)
            iii) UIBarButton selector (action/Target design pattern)
  2) New Message View Controller
            i) Text View Delegate (Delegate Design Pattern)
            ii) Done Button selector (action/Target design pattern)
            iii) Back Button selector (action/Target design pattern)

That is all about design pattern in iOS.

Please write to me if any query you have and you can share this tutorial with your friends.

Comments

Popular posts from this blog

Asynchronous Request with NSOperationQueue

Today post is about how to run a asynchronous task in NSOperationQueue.  Generally we do not run a Asynchronous task in NSOperationQueue. It is also not recommended for any programmer to do that. This post is only for learning purpose what will happen if we schedule a asynchronous task in a queue and how can we complete that task:). So let us move to the learning: NSOperationQueue: In iOS NSOperationQueue is a class, which provide a way to perform operation concurrently. We also have others way to perform concurrent operation: 1) GCD 2) NSThread 3) pThread NSOperationQueue is a wrapper on GCD, which provides a very convenient way to execute operation concurrently. To create a Queue for Operation you have to simply allocate a object of the class: NSOperationQueue * opertionQueue = [[ NSOperationQueue alloc ] init ]; For this post let suppose you are making a queue to handle all Http request in your application. So i want to create a queue in Handl...

Shake Effect in iOS

Animation Animation always capture the user attention. We can use animation to update things on the screen.  For developer also animations fascinated things to learn and implement. Today we will try shake effect with Various  API. CABasicAnimation: Here we animate view's frame y coordinate from one position to another position. It is simple example of changing the position with respect to time. CABasic Animation is deal with the single keyframe.                                        y(t) = y 0 + t*d(y) You can use CABasic Animation if you have to play with single value. You need to move object from  one position to another without any intermediate steps. CABasicAnimation * shakeAnimation = [CABasicAnimation animationWithKeyPath: @ "position" ]; shakeAnimation . duration = 0.05 ; shakeAnimation . autoreverses = YES; shakeAnimation . repe...

NSThread with Asynchronous Request

NSThread: It is class used in Cocoa framework to create a thread.You have to specify a target and selector to create a new thread in objective c. So the selector or method is main entry point of your thread.  Detail: What happen once the thread execute all the code in the method (Thread main routine)? Thread is terminated after execute all the code in the entry(its main routine) routine. So how we can run an asynchronous request on NSThread ? What is Async request? It is non blocking request which permit the application to do other task side by side as request is in continue. So it enhance parallelism in the application. Now question is how we can prepare a asynchronous request in iOS: - ( void ) startAsyncRequestWithUrl:( NSString *)urlString{     assert (urlString != nil && urlString. length > 0 );     NSURL * url = [[ NSURL alloc ] initWithString :urlString];     NSURLRequest * urlRequest = [[ NSURLReq...