O'Reilly logo

iOS 5 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

5.9. Performing a Task Only Once with GCD

Problem

You want to make sure a piece of code gets executed only once, during the lifetime of your application, even if it gets called more than once from different places in your code (such as the initializer for a singleton).

Solution

Use the dispatch_once function.

Discussion

Allocating and initializing a singleton is one of the tasks that has to happen exactly once during the lifetime of an app. I am sure you know of other scenarios where you had to make sure a piece of code was executed only once during the lifetime of your application.

GCD lets you specify an identifier for a piece of code when you attempt to execute it. If GCD detects that this identifier has been passed to the framework before, it won’t execute that block of code again. The function that allows you to do this is dispatch_once, which accepts two parameters:

Token

A token of type dispatch_once_t that holds the token generated by GCD when the block of code is executed for the first time. If you want a piece of code to be executed at most once, you must specify the same token to this method whenever it is invoked in the app. We will see an example of this soon.

Block object

The block object to get executed at most once. This block object returns no values and accepts no parameters.

Note

dispatch_once always executes its task on the current queue being used by the code that issues the call, be it a serial queue, a concurrent queue, or the main queue.

Here is an example:

static dispatch_once_t ...

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