Video Tutorial: Objective-C Protocols and Delegates

Learn about one of the most commonly used design patterns in Objective-C: protocols and delegates. By Ray Wenderlich.

Leave a rating/review
Save for later
Share

Contents

Hide contents

Video Tutorial: Objective-C Protocols and Delegates

1 min

Challenge

Your challenge is to add this new method to Stephanie.m:

- (void)isSad {
    [_delegate stephanieDidLookSad:self];
}

And this test code to AppDelegate.m:

//stephanie.delegate = vicki;
stephanie.delegate = freckles;
[stephanie isSad];

Then add the following code to make it all work:

  • Define a new StephanieDelegate protocol, with a single method stephanieDidLookSad:. Note you should define the protocol in a new file StephanieDelegate.h to avoid circular header dependencies.
  • Add a new property to Stephanie.h called delegate that represents a class that implements StephanieDelegate.
  • Mark Vicki and Freckles as implementing StephanieDelegate, and implement the delegate method to log out a message.

Download demo code

Download challenge solution

Helpful links

Errata

  • A few times in the video I refer to implementing the protocol. A better/more accurate term would have been conforming to the protocol.
  • I meant to include an example of declaring a type for a block, but forgot to. However, the demo code has an example of this that may be handy.
  • In my examples of enumerateObjectsUsingBlock:, I used this block declaration:
^(id obj, NSUInteger idx, BOOL *stop)

Then I cast obj to NSString* and stored it in a variable named game.

Although this is correct, another way of doing things that you should be aware of is that since you know the object in the array is an NSString*, you can declare the block like this and it will work, eliminating the need for the cast:

^(NSString *game, NSUInteger idx, BOOL *stop)

Contributors

Over 300 content creators. Join our team.