I have a few unit tests in which I'd like to test if a callback is called on the correct dispatch queue.
In Swift 2, I compared the label of the current queue to my test queue. However in Swift 3 the DISPATCH_CURRENT_QUEUE_LABEL
constant no longer exists.
I did find the dispatch_assert_queue
function. Which seems to be what I need, but I'm not sure how to call it.
My Swift 2 code:
let testQueueLabel = "com.example.my-test-queue" let testQueue = dispatch_queue_create(testQueueLabel, nil) let currentQueueLabel = String(UTF8String: dispatch_queue_get_label(DISPATCH_CURRENT_QUEUE_LABEL))! XCTAssertEqual(currentQueueLabel, testQueueLabel, "callback should be called on specified queue")
Update:
I got confused by the lack of autocomplete, but it is possible to use __dispatch_assert_queue
:
if #available(iOS 10.0, *) { __dispatch_assert_queue(test1Queue) }
While this does work for unit tests, it annoyingly stops the whole process with a EXC_BAD_INSTRUCTION
instead of only failing a test.
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].
The main dispatch queue is a globally available serial queue executing tasks on the application's main thread.
A dispatch queue that is bound to the app's main thread and executes tasks serially on that thread. A dispatch queue that executes tasks concurrently using threads from the global thread pool. A dispatch queue that executes tasks serially in first-in, first-out (FIFO) order.
There are two types of dispatch queues, serial dispatch queues and concurrent dispatch queues.
Use dispatchPrecondition(.onQueue(expectedQueue))
, the Swift 3 API replacement for the dispatch_assert_queue()
C API.
This was covered in the WWDC 2016 GCD session (21:00, Slide 128): https://developer.apple.com/videos/play/wwdc2016/720/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With