defer in Objective-C

Swift is a swift language and more and more developers are using it. And why not? It has so many advantages over Objective-C. But that doesn't make Objective-C any inferior. It has its own benefits. Swift is still being developed whereas Objective-C is a completely developed language. This is one of the best reasons companies like Facebook, Instagram, Whatsapp still want to keep on developing on Objective-C. I had interviewed at Facebook and the interviewer told me that he doesn't see any plan to move to Swift any sooner.

Swift has this particularly good, effective and skillful feature called "defer". Defer allows to run some code once you have reached the end of the current scope. Let's see an example below in Swift:

Swift code:

func useDefer() {
    defer {
        print("This will print last.")
    print("This will print first.")


This will print first.
This will print last.

Now the question is, can we do that in Objective-C?

Yes, we can!!

Let's create one.

Objective-C code:

@interface CustomDefer: NSObject

@implementation CustomDefer {
    @private void(^_deferBlock)();

+ (instancetype)block:(void(^)())block {
    CustomDefer *_defer = [CustomDefer new];
    _defer->_deferBlock = block ?: ^{};
    return _defer;

- (void)dealloc {

This implementation takes in the defer block and then runs it upon deallocation. Assuming that the ARC is being used, this object will deallocate after the end of the current scope is reached.

Now let's make use of this defer block.

Objective-C code:

id _1;
_1 = [CustomDefer block:^{
    NSLog(@"This will print last.");

NSLog(@"This will print first.");


This will print first.
This will print last.

Now, there are a couple of things that you must remember:

  1. You must save the CustomDefer instance to a variable. If you don't, the CustomDefer instance will deallocate right after it has been created.

  2. If you want to use multiple defer statements in your code, remember that the defer works from BOTTOM to TOP.

Enjoy coding!!

Inspired from: Derrick Ho

70 views0 comments

Recent Posts

See All