Get current dispatch queue?

Andrew picture Andrew · Jul 4, 2013 · Viewed 49.7k times · Source

I have a method which should support being called from any queue, and should expect to.

It runs some code in a background thread itself, and then uses dispatch_get_main_queue when it returns a value to its block argument.

I don't want it to force it onto the main queue if it wasn't when it entered the method. Is there a way to get a pointer to the current dispatch queue?

Answer

Palle picture Palle · Apr 17, 2015

If you are working with an NSOperationQueue, it can provide the current dispatch queue for you.

NSOperationQueue has the class function [NSOperationQueue currentQueue], which returns the current queue as a NSOperationQueue object. To get the dispatch queue object you can use [NSOperationQueue currentQueue].underlyingQueue, which returns your currrent queue as a dispatch_queue_t.

Swift 3:

if let currentDispatch = OperationQueue.current?.underlyingQueue {
    print(currentDispatch)
}

- works for main queue!