Wednesday, May 7, 2014

Quick Tutorial: Implementing Your Own Delegates in Objective-C

The delegate pattern is another simple, yet powerful design pattern. Many UI elements in iOS (i.e. UIScrollView, UITextField, UITableView,etc) use delegates to control their behavior. A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. The delegating object is often a responder object—that is, an object inheriting from NSResponder in AppKit or UIResponder in UIKit—that is responding to a user event. The delegate is an object that is delegated control of the user interface for that event, or is at least asked to interpret the event in an application-specific manner. For a more thorough description on delegates, refer to the Apple documentation.
In order to implement your own custom delegate protocol, you will need to 
  1. Modify the header (.h) file for MyClass (i.e. MyClass.h)
  2. Add the @protocol delaration
  3. Add a delegate @property
  4. Declare the methods that delegates can implement.















Next, make sure to check if the delegate is set and that it responds to the selector anytime you want to call the delegate within your implementation.









Next, for the classes that you want to conform to your new protocol, include MyClass.h header file and delegate protocol in the @interface





Finally, set its delegate to self somewhere and implement the delegate method




















View more documents from tasneemsayeed.

No comments: