O'Reilly logo

iOS 6 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

6.10. Grouping Tasks Together with GCD

Problem

You want to group blocks of code together and ensure that all of them get executed by GCD one by one, as dependencies of one another.

Solution

Use the dispatch_group_create function to create groups in GCD.

Discussion

GCD lets us create groups, which allow you to place your tasks in one place, run all of them, and get a notification at the end from GCD. This has many valuable applications. For instance, suppose you have a UI-based app and want to reload the components on your UI. You have a table view, a scroll view, and an image view. You want to reload the contents of these components using these methods:

- (void) reloadTableView{
  /* Reload the table view here */
  NSLog(@"%s", __FUNCTION__);
}

- (void) reloadScrollView{
  /* Do the work here */
  NSLog(@"%s", __FUNCTION__);
}

- (void) reloadImageView{
  /* Reload the image view here */
  NSLog(@"%s", __FUNCTION__);
}

At the moment these methods are empty, but you can put the relevant UI code in them later. Now we want to call these three methods, one after the other, and we want to know when GCD has finished calling these methods so that we can display a message to the user. For this, we should be using a group. You should know about four functions when working with groups in GCD:

dispatch_group_create

Creates a group handle. Once you are done with this group handle, you should dispose of it using the dispatch_release function.

dispatch_group_async

Submits a block of code for execution on a group. You ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required