Sunday, April 01, 2012

Steps to Delegate in iOS

I am back to the course of iOS Development by Stanford University. Last week, I watched Lesson 9 Table Views(October 25, 2011). Instructor Paul Hegarty mentioned 5 steps about Delegate at 1:04:15.

He talked the confusion for new developers when they use protocols.  The 5 steps are clear explanation on how to use and implement protocols. He also showed the steps in his demo.

  1. Create the @protocol
  2. Add delegate @property to delegator's public @interface
  3. Use delegate property inside delegator's implementation
  4. Set the delegate property somewhere inside the delegate's @implmentation
  5. Implement the protocol's method(s) in the delegate(include <> on @interface)

In the demo, the protocol CalculatorProgramsTableViewControllerDelegate is created in CalculatorProgramsTableViewController.h:

@class CalculatorProgramsTableViewController;

@protocol CalculatorProgramsTableViewControllerDelegate

- (void)calculatorProgramsTableViewController:(CalculatorPorgramTableViewController *)sender

In CalculatorProgramsTableViewController.h, the delegate is created in the controller as weak id <...> delegate:

@interface CalculatorProgramsTableViewController : UITableViewController
// Define a property delegate
@property (nonatomic, weak) id<CalculatorProgramsTableViewControlerDelegate> delegate;

In its .m file, the delegate property is defined by @synthesize delegate = _delegate.

@implementation CalculatorProgramsTableViewController
@synthesize delegate = _delegate;

In the event of a row cell being selected, the delegate is used:

#progma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView
    didSeelectRowAtIndexPath:(NSIndexPath *)indexPath
  id program = [self.programs objectAtIndex:indexPath.row];
  [self.delegate calculatorProgramsTableViewController:self

Next, where the delegate is set? in the event of controller segue. The delegate method is implemented in the controller:

@implementation CalculatorGraphViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue
  if ([segue.identifier isEqualToString:@"Show Favorite Graphics"]) {
    NSArray * programs = [[NSUserDefaults standardUserDefaults]
    [segue.destinationViewController setPrograms:programs];
    [segue.destinationViewController setDelegate:self]; // set delegate

Lastly, in order for the graphic view controller to know the change of a program, the controller has to implement the delegate method. The protocol method will be called when the delegate sends out its message: a row in table view being selected:

// in .h file, the protocal delegate is defined as the controller's interface
@interface CalculatorGraphViewController : NSOjbect

//In .m The protocol method is implemented
- (void)calculatorProgramsTableViewController:(CalculatorProgramsTableViewController *)sender
  self.calculatorProgram = program;

"That's all we need. OK!", Paul said.