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 ...
Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.