defer in Objective-c

Derrick Ho
1 min readMay 17, 2017

--

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Responses (3)

Write a response