defer in Objective-c
Swift has this nifty thing call defer which allows you to run some code once the you reach the end of the current scope. How do you do that in Objective-c?
@interface MyDefer : NSObject
+ (instancetype)block:(void(^)())block;
@end@implementation MyDefer {
@private void(^_deferBlock)();
}+ (instancetype)block:(void (^)())block {
MyDefer *_d = [MyDefer new];
_d->_deferBlock = block ?: ^{};
return _d;
}- (void)dealloc {
_deferBlock();
}
This implementation takes in the defer-block and then runs it upon deallocation. Assuming that you are using ARC, this object should deallocate after you reach the end of the current scope.
So how do you use this defer block?
id _0; _0 = [MyDefer block:^{
NSLog(@"Deferring 0");
}];
id _1; _1 = [MyDefer block:^{
NSLog(@"Deferring 1");
}];
id _2; _2 = [MyDefer block:^{
NSLog(@"Deferring 2");
}];NSLog(@"Stuff 1");
NSLog(@"Stuff 2");
NSLog(@"Stuff 3");// The console should print the following
Stuff 1
Stuff 2
Stuff 3
Deferring 2
Deferring 1
Deferring 0
One cavet to be aware of is that you MUST save the MyDefer instance to a variable. If you don’t, the MyDefer instance will deallocate right after it has been created.