Delegation
Delegation is the most important design pattern in Apple's frameworks. An object (say, a table view or a download task) doesn't decide everything itself: at key moments it asks or informs another object, its delegate. The delegate is defined by a protocol, held in a weak property, and its optional methods are checked with respondsToSelector:.
┌────────────┐ "did finish!" ┌────────────┐
│ Download │ ─────────────────► │ Controller │
│ (worker) │ ◄───────────────── │ (delegate) │
└────────────┘ "should retry?" └────────────┘Building a delegate protocol
The convention: name the protocol after the class plus Delegate, pass the sender as the first argument, and use did/will/should in the method names.
#import <Foundation/Foundation.h>
@class Download;
@protocol DownloadDelegate <NSObject>
- (void)download:(Download *)download didFinishWithBytes:(NSInteger)bytes;
@optional
- (void)download:(Download *)download didProgress:(double)fraction;
@end
@interface Download : NSObject
@property (nonatomic, copy) NSString *url;
@property (nonatomic, weak) id<DownloadDelegate> delegate; // weak!
- (void)start;
@end
@implementation Download
- (void)start {
NSInteger total = 4096;
for (NSInteger received = 1024; received <= total; received += 1024) {
if ([self.delegate respondsToSelector:@selector(download:didProgress:)]) {
[self.delegate download:self didProgress:(double)received / total];
}
}
[self.delegate download:self didFinishWithBytes:total];
}
@end
@interface Controller : NSObject <DownloadDelegate>
@end
@implementation Controller
- (void)download:(Download *)download didProgress:(double)fraction {
NSLog(@"%@: %.0f%%", download.url, fraction * 100);
}
- (void)download:(Download *)download didFinishWithBytes:(NSInteger)bytes {
NSLog(@"%@ finished: %ld bytes", download.url, (long)bytes);
}
@end
int main(void) {
@autoreleasepool {
Controller *controller = [Controller new];
Download *job = [Download new];
job.url = @"report.pdf";
job.delegate = controller;
[job start];
}
return 0;
}report.pdf: 25%
report.pdf: 50%
report.pdf: 75%
report.pdf: 100%
report.pdf finished: 4096 bytes
Download knows nothing about Controller; it only knows the protocol. You can reuse it with any delegate, or with none: messages to a nil delegate are simply ignored.
Why weak?
The controller usually owns the worker (it creates and keeps it). If the worker also held its delegate strongly, they would form a retain cycle. With a weak delegate, both are freed normally:
#import <Foundation/Foundation.h>
@protocol WorkerDelegate <NSObject>
- (void)workerDidFinish;
@end
@interface Worker : NSObject
@property (nonatomic, weak) id<WorkerDelegate> delegate;
@end
@implementation Worker
- (void)dealloc { NSLog(@"worker freed"); }
@end
@interface Screen : NSObject <WorkerDelegate>
@property (nonatomic, strong) Worker *worker; // the screen owns the worker
@end
@implementation Screen
- (instancetype)init {
self = [super init];
if (self) {
_worker = [Worker new];
_worker.delegate = self;
}
return self;
}
- (void)workerDidFinish { NSLog(@"screen notified"); }
- (void)dealloc { NSLog(@"screen freed"); }
@end
int main(void) {
@autoreleasepool {
Screen *screen = [Screen new];
[screen.worker.delegate workerDidFinish];
screen = nil; // closing the screen frees both
NSLog(@"after closing the screen");
}
return 0;
}screen notified
screen freed
worker freed
after closing the screen
Asking the delegate
Delegates don't only receive news; they also answer questions that customize behaviour (should… methods returning BOOL, or methods returning values). The worker supplies a sensible default when the delegate doesn't implement them:
#import <Foundation/Foundation.h>
@class Form;
@protocol FormDelegate <NSObject>
@optional
- (BOOL)form:(Form *)form shouldAcceptValue:(NSString *)value forField:(NSString *)field;
- (NSString *)titleForForm:(Form *)form;
@end
@interface Form : NSObject
@property (nonatomic, weak) id<FormDelegate> delegate;
- (void)submit:(NSDictionary *)values;
@end
@implementation Form
- (void)submit:(NSDictionary *)values {
NSString *title = @"Untitled form";
if ([self.delegate respondsToSelector:@selector(titleForForm:)]) {
title = [self.delegate titleForForm:self];
}
NSLog(@"== %@ ==", title);
for (NSString *field in [values.allKeys sortedArrayUsingSelector:@selector(compare:)]) {
BOOL ok = YES; // default: accept
if ([self.delegate respondsToSelector:@selector(form:shouldAcceptValue:forField:)]) {
ok = [self.delegate form:self shouldAcceptValue:values[field] forField:field];
}
NSLog(@"%@ = %@ %@", field, values[field], ok ? @"OK" : @"REJECTED");
}
}
@end
@interface SignupValidator : NSObject <FormDelegate>
@end
@implementation SignupValidator
- (NSString *)titleForForm:(Form *)form { return @"Sign up"; }
- (BOOL)form:(Form *)form shouldAcceptValue:(NSString *)value forField:(NSString *)field {
if ([field isEqualToString:@"email"]) {
return [value containsString:@"@"];
}
return value.length > 0;
}
@end
int main(void) {
@autoreleasepool {
NSDictionary *input = @{@"email": @"lee.example.com", @"name": @"Lee"};
Form *form = [Form new];
[form submit:input]; // no delegate: defaults
SignupValidator *validator = [SignupValidator new];
form.delegate = validator;
[form submit:input];
}
return 0;
}== Untitled form ==
email = lee.example.com OK
name = Lee OK
== Sign up ==
email = lee.example.com REJECTED
name = Lee OK
Delegation in Apple's frameworks
You'll meet this pattern constantly in UIKit (not runnable here):
@interface InboxViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
@end
@implementation InboxViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.dataSource = self; // "how many rows? what's in row 3?"
self.tableView.delegate = self; // "row 3 was tapped"
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.messages.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self openMessage:self.messages[indexPath.row]];
}
@end| Delegation vs. | When to prefer the other |
|---|---|
| blocks (completion handlers) | a single callback for a single operation |
| notifications | many unrelated listeners, or the sender shouldn't know them |
| subclassing | rarely: delegation customizes without inheriting |
Test yourself
Why are delegate properties declared weak?
- For speed
- To avoid a retain cycle with the object that owns the delegator
- Because protocols require it
- So the delegate can be nil
What is the conventional first parameter of a delegate method?
- self of the delegate
- The object sending the message (the delegator)
- An NSError
- A completion block
What happens if the delegate is nil when the worker sends it a message?
- Crash
- Exception
- Nothing: messages to nil are ignored
- The worker becomes its own delegate