Skip to content

Instantly share code, notes, and snippets.

Embed
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;
@end
#import "JNWGroupAsyncOperation.h"
@interface JNWGroupAsyncOperation()
@property (nonatomic, strong) dispatch_group_t dispatchGroup;
@end
@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_group_leave(dispatchGroup);
};
dispatch_group_enter(dispatchGroup);
dispatch_async(dispatch_get_main_queue(), ^{
operation(completion);
});
}
- (void)start {
if (self.groupCompletion != NULL) {
dispatch_group_notify(self.dispatchGroup, dispatch_get_main_queue(), self.groupCompletion);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.