Block Capture & __block
A block can use variables from the scope where it was written. How it captures them is one of the subtle parts of Objective-C, and the source of the most common ARC memory leak.
Captured values are copied
By default, a block captures a local C variable by value, at the moment the block is created. Later changes to the variable aren't seen by the block, and the block can't assign to it:
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
int discount = 10;
double (^applyDiscount)(double) = ^(double price) {
return price * (100 - discount) / 100.0; // captures discount = 10
};
discount = 50; // the block doesn't see this
NSLog(@"price after discount: %.2f", applyDiscount(80));
NSLog(@"discount variable is now %d", discount);
// ^{ discount = 0; } would not compile: captured variables are read-only
}
return 0;
}price after discount: 72.00
discount variable is now 50
__block: share the variable
Mark a variable __block to capture it by reference: the block and the surrounding code then share one variable, and the block can change it.
#import <Foundation/Foundation.h>
typedef NSInteger (^Counter)(void);
Counter makeCounter(NSInteger start, NSInteger step) {
__block NSInteger current = start; // lives on after the function returns
return ^NSInteger {
current += step;
return current;
};
}
int main(void) {
@autoreleasepool {
__block int clicks = 0;
void (^click)(void) = ^{ clicks++; };
click();
click();
click();
NSLog(@"clicks = %d", clicks);
Counter byTwo = makeCounter(0, 2);
Counter byTen = makeCounter(100, 10);
NSLog(@"%ld %ld %ld", (long)byTwo(), (long)byTwo(), (long)byTwo());
NSLog(@"%ld %ld", (long)byTen(), (long)byTen());
}
return 0;
}clicks = 3
2 4 6
110 120
Each call to makeCounter creates a new __block variable, so byTwo and byTen keep separate counts: that's a closure keeping private state.
Objects are captured strongly
For object pointers, the pointer is copied, but the block also keeps a strong reference to the object. Messages sent to the object inside the block affect the real object (no __block needed). Only reassigning the variable needs __block.
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSMutableArray *log = [NSMutableArray array];
void (^record)(NSString *) = ^(NSString *event) {
[log addObject:event]; // fine: we message the captured array
};
record(@"open");
record(@"save");
NSLog(@"log: %@", [log componentsJoinedByString:@", "]);
__block NSString *lastEvent = @"none";
void (^track)(NSString *) = ^(NSString *event) {
lastEvent = event; // reassigning needs __block
};
track(@"close");
NSLog(@"last event: %@", lastEvent);
}
return 0;
}log: open, save
last event: close
The self-capture retain cycle
Strong capture is what makes this code leak: the object owns the block (through a copy property) and the block owns the object (it captured it). Clang even warns about it:
#import <Foundation/Foundation.h>
@interface Timer : NSObject
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) void (^onTick)(void);
@end
@implementation Timer
- (void)dealloc { NSLog(@"%@ freed", _name); }
@end
int main(void) {
@autoreleasepool {
Timer *leaky = [Timer new];
leaky.name = @"leaky";
leaky.onTick = ^{ NSLog(@"tick from %@", leaky.name); }; // strong capture
leaky.onTick();
leaky = nil;
Timer *safe = [Timer new];
safe.name = @"safe";
__weak Timer *weakSafe = safe; // weak capture
safe.onTick = ^{ NSLog(@"tick from %@", weakSafe.name); };
safe.onTick();
safe = nil;
NSLog(@"done");
}
return 0;
}main.m:15:50: warning: capturing 'leaky' strongly in this block is likely to lead to a retain cycle [-Warc-retain-cycles]
leaky.onTick = ^{ NSLog(@"tick from %@", leaky.name); }; // strong capture
^~~~~
main.m:15:9: note: block will be retained by the captured object
leaky.onTick = ^{ NSLog(@"tick from %@", leaky.name); }; // strong capture
^~~~~
1 warning generated.
tick from leaky
tick from safe
safe freed
done
The compiler warning is printed above the program's output. At run time "leaky" is never freed, while "safe" is freed as soon as its variable is cleared.
The weak/strong dance
Inside a class, the same pattern uses self. If the block may run later (after an animation, a download), it also takes a temporary strong reference so self can't disappear halfway through:
__weak typeof(self) weakSelf = self;
self.completion = ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (!strongSelf) {
return; // the object is already gone
}
[strongSelf updateUI];
[strongSelf saveState];
};typeof(self) is a clang extension that gives the type of self, so the snippet can be pasted into any class.
Grand Central Dispatch
Blocks are also the unit of work for Grand Central Dispatch (GCD), Apple's API for running code concurrently. GCD isn't available in this course's verifier, so the following is for reading only:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{
NSData *data = [self loadBigFile]; // runs on a background thread
dispatch_async(dispatch_get_main_queue(), ^{
[self showData:data]; // UI work goes back to the main thread
});
});
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSLog(@"two seconds later");
});Blocks given to GCD don't create cycles by themselves: the queue releases the block after running it.
| Situation | Do |
|---|---|
| read a local C variable | nothing special |
| change a local variable from the block | __block |
| message an object | nothing special (captured strongly) |
block stored in a property of self and uses self |
capture __weak self |
| one-shot block (GCD, enumeration, most completion handlers) | strong capture is fine |
Test yourself
int x = 1; int (^f)(void) = ^{ return x; }; x = 5; What does f() return?
- 1
- 5
- 0
- It doesn't compile
When do you need __block on a captured object pointer?
- To send it messages
- To reassign the variable inside the block
- Always
- Never
Why does self.handler = ^{ [self save]; }; leak?
- Blocks are never freed
- self owns the block and the block owns self: a retain cycle
- save is called too often
- It doesn't leak