/AsyncBlockOperation

NSOperation subclass for async block.

Primary LanguageObjective-CMIT LicenseMIT

AsyncBlockOperation

Build Status CocoaPods

NSOperation subclass for async block.

  • Both compatible with Swift and Objective-C.
  • Light-weight. (4KB source code. Oh my god.)
  • Short-hand method extension NSOperationQueue.

At a Glance

Swift

import AsyncBlockOperation

let operation = AsyncBlockOperation { op in
    doSomeAsyncTaskWithCompletionBlock {
        op.complete() // complete operation
    }
}
queue.addOperation(operation)

Objective-C

#import <AsyncBlockOperation/AsyncBlockOperation.h>

AsyncBlockOperation *operation = [AsyncBlockOperation blockOperationWithBlock:^(AsyncBlockOperation *op) {
    [self doSomeAsyncTaskWithCompletionBlock:^{
        [op complete]; // complete operation
    }];
}];
[queue addOperation:operation];

Short-hand Method Extension

As NSBlockOperation does, AsyncBlockOperation supports NSOperationQueue extension to add async block operations quickly.

Swift

queue.addOperationWithAsyncBlock { op in
    op.complete()
}

Objective-C

[queue addOperationWithAsyncBlock:^(AsyncBlockOperation *op) {
    [op complete];
}];

Further Reading

Wanna get callback after all operations are done? Consider using NSOperationQueue+CompletionBlock which provides completionHandler for NSOperationQueue.

For example:

let queue = NSOperationQueue()
queue.completionHandler = {
    println("All images are loaded!")
}
queue.addOperationWithAsyncBlock { op in
    loadImage(imageURL1) { image in
        image.append(image)
        op.complete()
    }
}
queue.addOperationWithAsyncBlock { op in
    loadImage(imageURL2) { image in
        image.append(image)
        op.complete()
    }
}

Installation

I recommend you to use CocoaPods, a dependency manager for Cocoa.

Podfile

pod 'AsyncBlockOperation', '~> 1.0'

License

AsyncBlockOperation is under MIT license. See the LICENSE file for more info.