---
title: "#85: Grand Central Dispatch Basics 🚦"
url: https://littlebitesofcocoa.com/85-grand-central-dispatch-basics
author: Jake Marsh
published: 2015-09-18
topics: ["Foundation","Concurrency","Techniques"]
description: "Grand Central Dispatch is the name of Apple's collection of task concurrency functions in libdispatch. GCD (as it's often called) is packed full of..."
---

# #85: Grand Central Dispatch Basics 🚦

By Jake Marsh, September 18, 2015. HTML: https://littlebitesofcocoa.com/85-grand-central-dispatch-basics

_Grand Central Dispatch_ is the name of Apple's collection of **task concurrency** **functions** in **libdispatch**. _GCD_ (as it's often called) is packed full of interesting features involving **concurrency**, **queuing**, **timers**, and more. Let's dive in and take a look at some simple and common use cases:

## Common Usage

One of the most common ways to use _GCD_ is to hop to a **background queue** to do some work, then hop back to the **main queue** to update the UI:

``` swift
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
  let resizedAvatarImage = self.resizeImage(avatarImage)

  dispatch_async(dispatch_get_main_queue()) {
    self.avatarImageView.image = resizedAvatarImage
  }
}
```

## Dispatch Once

If we wanted to run some code in viewDidAppear: but only wanted it to run the first time, we could store some flag in a Bool property. Or just use _GCD_:

``` swift
struct Tokens {
  static var onceToken: dispatch_once_t = 0;
}
    
dispatch_once(&Tokens.onceToken) {
  self.initSomeState()
}
```

## Dispatch After

We can also easily wait a specified amount of time, then run some code. Here we'll use this technique to pop back to the previous **view controller** a quick "beat" after the user selects an an option in a **table view controller**. (As seen in many apps, including **Settings.app**):

``` swift
let delay = 0.5
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) {
  self.navigationController?.popViewControllerAnimated(true)
}
```
