Search code examples
iosxcodeobjective-c-2.0

Usage of dispatch_once usage for asynchronous processing


I am very confused about the usage of dispatch_once. Below two versions of code can give the same result. What is the difference when using dispatch_once?

Version 1

static dispatch_queue_t downloadQueue;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    downloadQueue = dispatch_queue_create("temp", 0);
});

Version 2

static dispatch_queue_t downloadQueue;
downloadQueue = dispatch_queue_create("dryapp", 0);

Solution

  • These two are completely different. The first one (with dispatch_once) lazily instantiates one instance of the download queue. If you call it again, the dispatch_once block will not be called again, only the first time you call it. This is an extremely useful pattern when you want to ensure that you have one and only one instance of the object in question (a queue in this case).

    The second pattern (with static variable and instantiated on a second line) has the static queue, but every time that second line of code is encountered, it will instantiate a new queue (releasing the previous one when the next one is instantiated).

    The first pattern is the one you presumably intended, to instantiate once and only once.