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
@protocol Playabledeclares required methods.NSObject <Playable>adopts it in the interface line.id<Playable>types by capability instead of class.
Keywords and builtins used here
NSObjectNSStringPlayableSingleidintplayreturnvoid
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.
Step 1 of 3 in Protocols & dynamism, step 19 of 27 in Language basics.