Tuesday, November 19, 2013

The most important design patterns in iOS

Today lets see the most important basic design patterns in iOS,

design pattern solves a common software engineering problem. Patterns are abstract designs, not code. When you adopt a design, you adapt its general pattern to your specific needs. No matter what type of app you’re creating, Understanding design patterns helps you use frameworks more effectively and allows you to write apps that are more reusable, more extensible, and easier to change.

The most important design patterns you must know are
1) MVC (Model View Controller)
2) Target Action
3) Delegation
4) Blocks

1) MVC (Model View Controller)
In this pattern, model keep track of your app’s data, views display your user interface and make up the content of an app, and controllers manage your views. 
Example:
In an iOS app, your Interface builder(.xib) files are views, your interface(.h) and implementation(.m) file is a Controller and your database (CoreData or SQLite or SQL Server) is nothing as a Model.

Advantages:
This pattern separates the data objects in the model from the views used to present that data. This separation promotes code reuse by making it possible to swap out your views as needed and is especially useful when creating universal apps—that is, apps that can run on both iPad and iPhone.

2) Target Action
Target-action is a conceptually simple design in which one object sends a message to another object when a specific event occurs.

Example:
Consider an UIButton in a view say Login button on a UIView, on TouchUpInside event you are calling a selector method where you actually perform login action, here the Target is generally self or whichever the controller(XYZViewController) is handling the action and Action is Login in this example.

3) Delegation
Delegation is a simple and powerful pattern in which one object in an app acts on behalf of, or in coordination with, another object. 

The delegate of a framework class is automatically registered as an observer of notifications posted by the delegating object.The delegate need only implement a notification method declared by the framework class to receive a particular notification message.

Example:
Consider UITableView class where didSelectRowAtIndexPath: is a delegate method of UITableView,
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
This method tells the delegate that the specified row is now selected. The delegate handles selections in this method

Attribute tableView: A table-view object informing the delegate about the new row selection.

Attribute indexPath:An index path locating the new selected row in tableView.

By the help of this delegate method of UITableView, you will come to know which row of your table user has selected if your table is adopting and confirming to UITableView protocol, i.e; <UITableViewDelegate> in your interface(.h) file and yourTableViewObj.delegate = self; in your implementation(.m) file.

Advantage of this delegate method is No pain for a programmer to get the user selected row index.

4) Blocks
Blocks are a language-level feature, which allow you to create distinct segments of code that can be passed around to methods or functions as if they were values. Blocks are Objective-C objects, which means they can be added to collections like NSArray or NSDictionary. They also have the ability to capture values from the enclosing scope,

Example:
The syntax to define a block literal uses the caret symbol (^), like this:
1)^{
NSLog(@”This is a block”);
    };
In the above example, the block doesn’t return any value, and doesn’t take any arguments.

2) use the operator to declare a block variable and to indicate the beginning of a block literal. The body of the block itself is contained within {}, as shown in this example
int multiplier = 4;
int (^myBlock)(int) = ^(int num) {
    return num * multiplier;
};

the block is able to make use of variables from the same scope in which it was defined.
In the above example myBlock is a block name, which returns an integer type, it takes an single argument of type int, num is an argument name and stuffs inside flower braces’{}’ is the body of the block and a block always ends with a semicolon(;).
Advantages:
- A block is commonly used in place of a call back function.
- It saves you having to create your own threads and maintain the state of each thread, manage locks & etc.
- Blocks can be used by multiple threads.


In addition to the above mentioned design patterns iOS is having even more design patterns like Abstract Factory,Adapter,Chain of Responsibility,Command,Composite,Decorator,Facade,Iterator,Mediator,Memento,Observer,Proxy,Receptionist,Singleton to know about these additional design patterns you can go through this Apples Official documentation https://developer.apple.com/legacy/library/documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaDesignPatterns/CocoaDesignPatterns.html#//apple_ref/doc/uid/TP40002974-CH6-SW6

Hope this post was helpful, any comments or suggestions is acceptable.

6 comments:

  1. its a good one Arun. I have some questions in my Mind i.e if Block comes under a Design patten then Where & how to Use it?

    ReplyDelete
    Replies
    1. @ Jyotiraditya Dhalmahapatra thank you.. :) , well for your question so as to answer in a brief its quite difficult, where to use; its up to your comfort level, some examples are you can use blocks instead of writing a selector method, you can use blocks (completion handler) instead of delegate design pattern(I will be posting a post on this whenever I will get a time with a sample project), while using queues (GCD) this pattern is used and many other places as well. And for how to use you need to learn blocks syntax first and be familiar with it. Hope it helps.

      Delete
  2. Clear and simple explanation and easy to understand.

    ReplyDelete