Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 38 ยท Protocols, Categories and Blocks

Protocols and Delegation

Learn Objective-C protocols - declaring and adopting them, @required and @optional methods, the delegate pattern, conformsToProtocol, id<Protocol> types and a C vtable stand-in.

Objective-C has single inheritance: a class has exactly one superclass. Yet a table view needs "something that provides rows" and a download needs "something to tell when it is done", and those somethings can be any class. A protocol is the answer. It is a named list of method declarations, with no implementation and no instance variables, that any class can promise to implement. It is the equivalent of an interface in Java or C#.

Protocols are everywhere in Cocoa: NSCopying, NSCoding, UITableViewDataSource, NSURLSessionDelegate. They are the foundation of the delegate pattern, which is how one object customizes the behavior of another without subclassing it.

Declaring and adopting a protocol

OBJECTIVEC
@protocol Drawable <NSObject>
@required
- (void)draw;
- (CGFloat)area;
@optional
- (NSString *)caption;
@end

@interface Circle : NSObject <Drawable>
@property (nonatomic) CGFloat radius;
@end

@implementation Circle
- (void)draw { NSLog(@"circle r=%.1f", self.radius); }
- (CGFloat)area { return M_PI * self.radius * self.radius; }
// caption is optional: Circle may leave it out
@end
  • @protocol Name <NSObject> says the protocol also includes everything in NSObject's protocol (isEqual:, respondsToSelector:, and so on). You almost always want this.
  • @required (the default) methods must be implemented, or the compiler warns.
  • @optional methods may be missing; callers must check before calling.
  • A class adopts a protocol by listing it in angle brackets after its superclass: @interface Circle : NSObject <Drawable, NSCopying>.

Typing with protocols

You can declare a variable to be "any object that conforms to this protocol":

OBJECTIVEC
id<Drawable> shape = [[Circle alloc] init];
[shape draw];                     // the compiler knows draw exists

NSArray<id<Drawable>> *scene = @[circle, square, triangle];
for (id<Drawable> item in scene) {
    [item draw];
}

id<Drawable> is better than id because the compiler can check your messages, and better than a class name because it does not care what the class is. At runtime you can ask:

OBJECTIVEC
if ([obj conformsToProtocol:@protocol(Drawable)]) { ... }
if ([obj respondsToSelector:@selector(caption)]) { ... }  // for optional methods

Optional methods

Calling an unimplemented optional method crashes with "unrecognized selector", so always check:

OBJECTIVEC
if ([shape respondsToSelector:@selector(caption)]) {
    NSLog(@"%@", [shape caption]);
}

This check is cheap, and it is how delegates work: a delegate implements only the callbacks it cares about.

The delegate pattern

A delegate is an object that another object notifies about events or asks for decisions. The owner defines a protocol, holds a weak reference to whoever implements it, and calls it at the right moments.

OBJECTIVEC
@class Downloader;

@protocol DownloaderDelegate <NSObject>
@optional
- (void)downloader:(Downloader *)d didReceiveProgress:(double)fraction;
- (BOOL)downloaderShouldRetry:(Downloader *)d;
@required
- (void)downloader:(Downloader *)d didFinishWithData:(NSData *)data;
@end

@interface Downloader : NSObject
@property (nonatomic, weak) id<DownloaderDelegate> delegate;  // weak: avoids a cycle
- (void)start;
@end

Conventions: the first parameter is the sender (so one delegate can serve several objects), method names say what happened (did..., will...) or ask a question (should...), and the delegate property is weak. Inside Downloader:

OBJECTIVEC
- (void)reportProgress:(double)p {
    if ([self.delegate respondsToSelector:@selector(downloader:didReceiveProgress:)]) {
        [self.delegate downloader:self didReceiveProgress:p];
    }
}

What a protocol is underneath: a table of function pointers

In C there are no protocols, but you can build the same thing: a struct of function pointers (a vtable) that each "class" fills in. The stand-in below defines a Drawable protocol with a required and an optional method, adopts it with two "classes", and checks the optional one like respondsToSelector:.

C Stand-in: a protocol as a table of function pointers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The Objective-C runtime does something similar but dynamic: it looks up each message by name in the receiver's class when it is sent (see the runtime).

The delegate pattern in C

A delegate is just a callback table plus a context pointer. The downloader below reports progress to whoever registered, and survives having no delegate at all, like sending a message to nil.

C Stand-in: a delegate with optional callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Protocol inheritance and common Cocoa protocols

A protocol can extend others: @protocol Shape <Drawable, NSCopying>. Any adopter must satisfy every protocol in the chain. Protocols worth knowing early:

  • NSCopying and NSMutableCopying: implement copyWithZone: so [obj copy] works and copy properties can store your type.
  • NSCoding / NSSecureCoding: archive an object to disk.
  • NSFastEnumeration: makes for (x in collection) work for your class.
  • NSObject: the root protocol for isEqual:, hash, description.

Lightweight generics (NSArray<id<Drawable>> *) let the compiler check element types, though they are erased at runtime.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a protocol contain?

    A protocol declares a contract; adopting classes provide the implementations.
  2. 2. Why check respondsToSelector: before calling an optional method?

    An optional method may not be implemented, and sending it anyway crashes.
  3. 3. Why is the delegate property usually weak?

    The delegate often owns the object that calls it, so a strong reference would form a cycle.
  4. 4. Which type means 'any object that adopts Drawable'?

    id<Protocol> and NSObject<Protocol> * both constrain the object by protocol, not by class.

Summary

  • A protocol is a named set of method declarations that unrelated classes can adopt.
  • @required and @optional control what adopters must provide; check optional methods with respondsToSelector:.
  • Delegation uses a protocol plus a weak delegate property.
  • id<Protocol> types let the compiler check messages without fixing the class.

Next: Categories and Class Extensions