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
#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:
#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:
#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).
#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>. Thenid<YourProtocol>variables can also receiverespondsToSelector:,isEqual:and other basic messages without warnings.
Test yourself
How do you declare that class Car adopts protocol Drivable?
- @interface Car : Drivable
- @interface Car : NSObject <Drivable>
- @interface Car implements Drivable
- @protocol Car <Drivable>
What must a caller do before sending an @optional protocol method?
- Nothing
- Check respondsToSelector:
- Check conformsToProtocol:
- Cast to the class
Which protocol must a class adopt so that [obj copy] works?
- NSCoding
- NSObject
- NSCopying
- NSFastEnumeration