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);
These two are completely different. The first one (with
dispatch_once
) lazily instantiates one instance of the download queue. If you call it again, thedispatch_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 thestatic
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.