AIDefer

A defer statement for Objective-C, similar to Go's defer.

MIT License

Stars
11

AIDefer is a code execution deferring system inspired on Go's defer statement. As an alternative you may want to consider using libextobjc's @onExit

Usage

Use defer to postpone the execution of a block. This is useful when dealing with resources that need to be released at a later point. Here is an example for using a lock:

- (Person*)personAtIndex:(NSUInteger)index {
    [_lock lock];
    defer(^() {
        [_lock unlock];
    });
    
    return [_array objectAtIndex:index];
}

The lock is aquired at the start of the method and the unlock is postponed until the method returns. See the blog post for more information.

Installation

To use in your project simply copy the AIDefer.h and AIDefer.m files into your project. If you are using CocoaPods add this to your Podfile:

pod "AIDefer", "~> 1.0.2"