Get current dispatch queue?
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!
With the deprecation of dispatch_get_current_queue()
there is effectively no way to know what queue you're executing on. If you peruse the GCD sources, you'll eventually see that this is because there may be multiple answers to the question "what queue am I executing on?" (Because queues eventually target one of the global queues, etc.)
If you want to guarantee that a future block is run on a specific queue, then the only way is to make your API accept a queue as a parameter along with the completion block. This lets the caller decide where the completion gets executed.
If simply knowing whether the caller is on the main thread or not is enough, you can use +[NSThread isMainThread]
to find out. In the common case, all blocks executing on the main GCD queue will be executing on the main thread. (One exception to this rule is if your application uses dispatch_main()
in lieu of a main run loop, you will have to use dispatch_get_specific
and friends to detect with certainty that you are executing on the main queue -- this is a comparatively rare circumstance.) More commonly, note that not all code that executes on the main thread executes on the main queue via GCD; GCD is subordinate to the main thread runloop. For your specific case it sounds like that might be enough.