Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
basic async operations
#import <Foundation/Foundation.h>
typedef void (^JNWGroupAsyncOperationCompletion)();
@interface JNWGroupAsyncOperation : NSObject
// The completion block that will be fired when all operations have completed.
@property (nonatomic, copy) void(^groupCompletion)();
// Adds an asynchronous operation and starts it on the main thread. The completion block _must_
// be called when the async operation has completed, otherwise the entire operation will never complete.
- (void)addAsynchronousOperation:(void (^)(JNWGroupAsyncOperationCompletion completion))operation;
// Waits for the operations to complete, then runs the `groupCompletion` block. If the operations
// have already completed by the time this is called, the completion will be called immediately.
- (void)start;
#import "JNWGroupAsyncOperation.h"
@interface JNWGroupAsyncOperation()
@property (nonatomic, strong) dispatch_group_t dispatchGroup;
@implementation JNWGroupAsyncOperation
- (instancetype)init {
self = [super init];
self.dispatchGroup = dispatch_group_create();
return self;
- (void)addAsynchronousOperation:(void (^)(JNWGroupAsyncOperationCompletion))operation {
dispatch_group_t dispatchGroup = self.dispatchGroup;
void (^completion)() = ^{
dispatch_async(dispatch_get_main_queue(), ^{
- (void)start {
if (self.groupCompletion != NULL) {
dispatch_group_notify(self.dispatchGroup, dispatch_get_main_queue(), self.groupCompletion);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment