5.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_createCreates a group handle. Once you are done with this group handle, you should dispose of it using the
dispatch_releasefunction.dispatch_group_asyncSubmits a block of code for execution on a group. You ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access