1

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);

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0
dispatch_once

No there is no such as big difference as you can see that there is way to programming methods.Here is the link might be helpful for you for reading

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.