Skip to content

Instantly share code, notes, and snippets.

@AdibContractorCC
Last active August 29, 2015 14:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AdibContractorCC/3816f807b36ef4345bd0 to your computer and use it in GitHub Desktop.
Save AdibContractorCC/3816f807b36ef4345bd0 to your computer and use it in GitHub Desktop.
Usage of dispatch_group_notify in Objective-C
#import "AppDelegate.h"
@interface AppDelegate ()
@property (nonatomic, strong) dispatch_group_t dispatchGroup;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.dispatchGroup = dispatch_group_create();
__weak typeof(self) weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_enter(weakSelf.dispatchGroup);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"block 1");
dispatch_group_leave(weakSelf.dispatchGroup);
[weakSelf groupNotifier];
});
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_enter(weakSelf.dispatchGroup);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"block 2");
dispatch_group_leave(weakSelf.dispatchGroup);
[weakSelf groupNotifier];
});
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_enter(weakSelf.dispatchGroup);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"block 3");
dispatch_group_leave(weakSelf.dispatchGroup);
[weakSelf groupNotifier];
});
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_group_enter(weakSelf.dispatchGroup);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"block 4");
dispatch_group_leave(weakSelf.dispatchGroup);
[weakSelf groupNotifier];
});
});
return YES;
}
- (void)groupNotifier {
dispatch_group_notify(self.dispatchGroup, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(@"Does this only print once?");
});
}
@end
/* This results in the following trace:
2015-04-08 15:49:52.264 DispatchGroupTest[3491:1504519] block 2
2015-04-08 15:49:52.264 DispatchGroupTest[3491:1504519] block 3
2015-04-08 15:49:52.265 DispatchGroupTest[3491:1504519] block 4
2015-04-08 15:49:52.265 DispatchGroupTest[3491:1504519] block 1
2015-04-08 15:49:52.265 DispatchGroupTest[3491:1505522] Does this only print once?
2015-04-08 15:49:52.265 DispatchGroupTest[3491:1505523] Does this only print once?
2015-04-08 15:49:52.265 DispatchGroupTest[3491:1505522] Does this only print once?
2015-04-08 15:49:52.265 DispatchGroupTest[3491:1505523] Does this only print once?
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment