TExcelTAD
Home › Objective-C › Protocols

Protocols

A protocol is a list of methods (and properties) that a class promises to implement, without saying how. It's like an interface in Java or C#, or a protocol in Swift. Any class, from any part of the hierarchy, can adopt a protocol, which is how Objective-C shares behaviour without multiple inheritance.

Declaring and adopting

objc · try it yourself
#import <Foundation/Foundation.h>

@protocol Shape <NSObject>          // protocols usually inherit the NSObject protocol
- (double)area;
- (NSString *)name;
@end

@interface Circle : NSObject <Shape>   // adopt in angle brackets
@property (nonatomic) double radius;
@end
@implementation Circle
- (double)area { return M_PI * self.radius * self.radius; }
- (NSString *)name { return @"circle"; }
@end

@interface Rect : NSObject <Shape>
@property (nonatomic) double width, height;
@end
@implementation Rect
- (double)area { return self.width * self.height; }
- (NSString *)name { return @"rectangle"; }
@end

int main(void) {
    @autoreleasepool {
        Circle *c = [Circle new];
        c.radius = 1;
        Rect *r = [Rect new];
        r.width = 3;
        r.height = 2;

        NSArray<id<Shape>> *shapes = @[c, r];
        for (id<Shape> s in shapes) {
            NSLog(@"%@: %.2f", [s name], [s area]);
        }
    }
    return 0;
}
circle: 3.14
rectangle: 6.00

id<Shape> means "any object that conforms to Shape". The compiler now checks that you only send Shape messages, and warns if a class claims to adopt the protocol but forgets a required method.

Required and optional methods

Methods are @required by default. Methods after @optional may or may not be implemented, so callers must check with respondsToSelector: before sending them:

objc · try it yourself
#import <Foundation/Foundation.h>

@protocol Exportable <NSObject>
@required
- (NSString *)exportAsText;
@optional
- (NSString *)exportAsCSV;
@end

@interface Note : NSObject <Exportable>
@end
@implementation Note
- (NSString *)exportAsText { return @"Buy milk"; }
@end

@interface Budget : NSObject <Exportable>
@end
@implementation Budget
- (NSString *)exportAsText { return @"Rent: 900, Food: 300"; }
- (NSString *)exportAsCSV { return @"Rent,900\nFood,300"; }
@end

void export(id<Exportable> item) {
    NSLog(@"text: %@", [item exportAsText]);
    if ([item respondsToSelector:@selector(exportAsCSV)]) {
        NSLog(@"csv:\n%@", [item exportAsCSV]);
    } else {
        NSLog(@"(no CSV export)");
    }
}

int main(void) {
    @autoreleasepool {
        export([Note new]);
        export([Budget new]);
    }
    return 0;
}
text: Buy milk
(no CSV export)
text: Rent: 900, Food: 300
csv:
Rent,900
Food,300

Protocols with properties, and conformance checks

A protocol can declare properties; the adopting class must provide them (often by redeclaring them as @property, so they are synthesized). At run time conformsToProtocol: tells you whether a class adopted a protocol:

objc · try it yourself
#import <Foundation/Foundation.h>

@protocol Identifiable <NSObject>
@property (nonatomic, copy, readonly) NSString *identifier;
@end

@interface User : NSObject <Identifiable>
@property (nonatomic, copy, readonly) NSString *identifier;
- (instancetype)initWithIdentifier:(NSString *)identifier;
@end
@implementation User
- (instancetype)initWithIdentifier:(NSString *)identifier {
    self = [super init];
    if (self) { _identifier = [identifier copy]; }
    return self;
}
@end

int main(void) {
    @autoreleasepool {
        NSArray *things = @[[[User alloc] initWithIdentifier:@"u-17"], @"just a string"];
        for (id thing in things) {
            if ([thing conformsToProtocol:@protocol(Identifiable)]) {
                id<Identifiable> item = thing;
                NSLog(@"identifiable: %@", item.identifier);
            } else {
                NSLog(@"not identifiable: %@", thing);
            }
        }
        NSLog(@"protocol name: %@", NSStringFromProtocol(@protocol(Identifiable)));
    }
    return 0;
}
identifiable: u-17
not identifiable: just a string
protocol name: Identifiable

Adopting several protocols

A class can adopt any number of protocols, separated by commas. Foundation's own protocols are a common choice: NSCopying (support copy), NSSecureCoding (archiving), NSFastEnumeration (support for … in).

objc · try it yourself
#import <Foundation/Foundation.h>

@protocol Describable <NSObject>
- (NSString *)summary;
@end

@interface Coordinate : NSObject <NSCopying, Describable>
@property (nonatomic) double lat, lon;
@end

@implementation Coordinate
- (id)copyWithZone:(NSZone *)zone {
    Coordinate *c = [[Coordinate allocWithZone:zone] init];
    c.lat = self.lat;
    c.lon = self.lon;
    return c;
}
- (NSString *)summary {
    return [NSString stringWithFormat:@"%.4f, %.4f", self.lat, self.lon];
}
@end

int main(void) {
    @autoreleasepool {
        Coordinate *home = [Coordinate new];
        home.lat = 51.5007;
        home.lon = -0.1246;

        Coordinate *saved = [home copy];   // works because we adopted NSCopying
        home.lat = 0;
        NSLog(@"home:  %@", [home summary]);
        NSLog(@"saved: %@", [saved summary]);
        NSLog(@"different objects? %d", home != saved);
    }
    return 0;
}
home:  0.0000, -0.1246
saved: 51.5007, -0.1246
different objects? 1
Syntax Meaning
@protocol Name <NSObject> … @end declare a protocol
@interface C : Super <P1, P2> adopt protocols
id<P> any object conforming to P
NSObject<P> * an NSObject subclass conforming to P
@protocol(P) the protocol object, for conformsToProtocol:
@required / @optional sections inside a protocol

Tip: Make your protocols inherit from <NSObject>. Then id<YourProtocol> variables can also receive respondsToSelector:, isEqual: and other basic messages without warnings.

Test yourself

How do you declare that class Car adopts protocol Drivable?

  1. @interface Car : Drivable
  2. @interface Car : NSObject <Drivable>
  3. @interface Car implements Drivable
  4. @protocol Car <Drivable>

What must a caller do before sending an @optional protocol method?

  1. Nothing
  2. Check respondsToSelector:
  3. Check conformsToProtocol:
  4. Cast to the class

Which protocol must a class adopt so that [obj copy] works?

  1. NSCoding
  2. NSObject
  3. NSCopying
  4. NSFastEnumeration