iOS engineer who likes clean, simple designs and sans-serif.

Loading

iOS Protocol + Delegation CheatSheet

My cheatsheet on how to set up Protocols + Delegation in iOS:

  1. TargetViewController.h:

    • Create protocol 
      @protocol TargetViewControllerDelegate
      @required
      …methods…
      @end
    • Create delegate
      @property (weak, nonatomic) id delegate;
  2. SourceViewController.h:

    • #import “TargetViewController.h”
    • Conform to protocol:  <TargetViewControllerDelegate>
  3. SourceViewController.m:

    • Add #pragma mark – TargetViewController Delegate
    • Define methods and dismiss TargetViewController
      [self dismissViewControllerAnimated:YES completion:nil];
    • In prepareForSegue,
      if ([segue.destinationViewController isKindOfClass: [TargetViewController class]) }
      TargetViewController *targetViewController = segue.destinationViewController;
      targetViewController.delegate = self;
      }
  4. TargetViewController.m:

    • Define methodName as [self.delegate methodName];

Leave a Comment