Saturday, December 26, 2015

What is Delegation in iOS?

Delegation is a design pattern in which one object sends messages to another object—specified as its delegate - to ask for input or to notify it that an event is occurring. Delegation is often used as an alternative to class inheritance to extend the functionality of reusable objects. For example, before a window changes size, it asks its delegate whether the new size is ok. The delegate replies to the window, telling it that the suggested size is acceptable or suggesting a better size. (For more details on window resizing, see the windowWillResize:toSize: message.)

Delegate methods are typically grouped into a protocol. A protocol is basically just a list of methods. The delegate protocol specifies all the messages an object might send to its delegate. If a class conforms to (or adopts) a protocol, it guarantees that it implements the required methods of a protocol. (Protocols may also include optional methods).In this application, the application object tells its delegate that the main startup routines have finished by sending it the applicationDidFinishLaunching: message. The delegate is then able to perform additional tasks if it wants.

Example:
Let's assume an object A calls an object B to perform an action. Once the action is complete, object A should know that B has completed the task and take necessary action. This is achieved with the help of delegates.

The key concepts in the above example are −
A is a delegate object of B.
B will have a reference of A.
A will implement the delegate methods of B.
B will notify A through the delegate methods.