Skip to content

Instantly share code, notes, and snippets.

@hsleedevelop
Created February 20, 2018 05:50
Show Gist options
  • Save hsleedevelop/50bb1f68342492f64489e31443490361 to your computer and use it in GitHub Desktop.
Save hsleedevelop/50bb1f68342492f64489e31443490361 to your computer and use it in GitHub Desktop.
// create results array
__block NSMutableArray* results = [NSMutableArray new];
// create serial queue
dispatch_queue_t queue = dispatch_queue_create("myQueue", 0);
for(NSInteger i = 0; i < 10; i++) {
// enqueue operation in queue
dispatch_async(queue, ^{
// create semaphore
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
// do something async, I do use another dispatch_queue for example
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
// wrap in autoreleasepool to release memory upon completion
// in your case wrap the resultBlock in autoreleasepool
@autoreleasepool {
// here for example the nested operation sleeps for two seconds
sleep(2);
// add the operation result to array
// I construct an array of strings for example
[results addObject:[NSString stringWithFormat:@"Operation %d has finished.", i]];
// signal that nested async operation completed
// to wake up dispatch_semaphore_wait below
dispatch_semaphore_signal(sema);
}
});
// wait until the nested async operation signals that its finished
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
NSLog(@"Finished single operation.");
});
}
// will be called once all operations complete
dispatch_async(queue, ^{
NSLog(@"Finished all jobs.");
NSLog(@"Results: %@", results);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment