Wednesday, January 09, 2013

Delegation in iOS


When you first start out programming iOS application, you’ll most likely notice the continued use of “delegates” throughout the SDK. The delegation pattern is not a pattern specific to iOS, but depending on what programming background you’ve had, it might not be immediately obvious as to what advantages this pattern provides, and why it seems to be used so often.
The basic idea of delegation, is that a controller defines a protocol (a set of method definitions) that describe what a delegate object must do in order to be allowed to respond to a controller’s events. The protocol is a contract where the delegator says “If you want to be my delegate, then you must implement these methods”. What this does is allows the controller to call methods on it’s delegate with the knowledge that the delegate will respond to the method calls. The delegate can be of any object type, so the controller is not coupled to a particular Object, but it can still be sure that the delegate will respond when it tries to tell it things.
Pros
  • Very strict syntax. All events to be heard are clearly defined in the delegate protocol.
  • Compile time Warnings / Errors if a method is not implemented as it should be by a delegate.
  • Protocol defined within the scope of the controller only.
  • Very traceable, and easy to identify flow of control within an application.
  • Ability to have multiple protocols defined one controller, each with different delegates.
  • No third party object required to maintain / monitor the communication process.
  • Ability to receive a returned value from a called protocol method. This means that a delegate can help provide information back to a controller.
Cons
  • Many lines of code required to define: 1. the protocol definition, 2. the delegate property in the controller, and 3. the implementation of the delegate method definitions within the delegate itself.
  • Need to be careful to correctly set delegates to nil on object deallocation, failure to do so can cause memory crashes by calling methods on deallocated objects.
  • Although possible, it can be difficult and the pattern does not really lend itself to have multiple delegates of the same protocol in a controller (telling multiple objects about the same event)

Source 
http://blog.shinetech.com/2011/06/14/delegation-notification-and-observation/

No comments:

Swift Operators - Basic Part 3 (Range operators in swift)

Range Operators: Closed Range operators  Half-Open Range Operators One-Sided Ranges Closed Range Operators:  a...b It defines...