Created
July 11, 2013 00:55
-
-
Save jwilling/5971616 to your computer and use it in GitHub Desktop.
basic async operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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