Reading — step 1 of 4
Learn
~1 min readCategories and Protocols
A protocol declares methods that conforming classes must (or may) implement — like an interface.
@protocol Greetable <NSObject>
- (NSString *)greeting; // required by default
@optional
- (NSString *)formalGreeting; // marked optional
@end
@interface English : NSObject <Greetable> // declare conformance
@end
@implementation English
- (NSString *)greeting { return @"Hello"; }
@end
The <Greetable> after : NSObject declares conformance. The compiler warns if required methods are missing.
Multiple protocols — separated by commas:
@interface MyClass : NSObject <Greetable, NSCopying, NSCoding>
@end
Protocol-typed variables:
id<Greetable> obj = [English new];
[obj greeting];
id is the dynamic Objective-C type. id<Protocol> constrains it to objects conforming to that protocol.
Checking conformance at runtime:
if ([obj conformsToProtocol:@protocol(Greetable)]) {
[obj greeting];
}
if ([obj respondsToSelector:@selector(formalGreeting)]) {
[obj formalGreeting];
}
@selector is a compile-time reference to a method name. Used heavily for callback registration (target/action pattern).
Delegate pattern — Cocoa's main use of protocols:
@protocol DownloadDelegate
- (void)downloadDidFinish:(NSData *)data;
- (void)downloadDidFail:(NSError *)error;
@end
// Class holds a weak reference to its delegate, calls back on events.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…