typestar

Protocols in Objective-C

A contract classes adopt in angle brackets.

#import <Foundation/Foundation.h>

// A protocol is a contract; classes adopt it in angle brackets.
@protocol Playable
- (NSString *)play;
@end

@interface Single : NSObject <Playable>
@end

@implementation Single
- (NSString *)play {
    return @"45 rpm, three minutes of joy";
}
@end

int main(void) {
    @autoreleasepool {
        id<Playable> disc = [[Single alloc] init];
        NSLog(@"%@", [disc play]);
    }
    return 0;
}

How it works

  1. @protocol Playable declares required methods.
  2. NSObject <Playable> adopts it in the interface line.
  3. id<Playable> types by capability instead of class.

Keywords and builtins used here

The run, in numbers

Lines
23
Characters to type
402
Tokens
78
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 72 seconds.

Type this snippet

Step 1 of 3 in Protocols & dynamism, step 19 of 27 in Language basics.

← Previous Next →

Protocols in other languages