Calling a method on the main thread? Calling a method on the main thread? multithreading multithreading

Calling a method on the main thread?


Objective-C

dispatch_async(dispatch_get_main_queue(), ^{    [self doSomething];});

Swift

DispatchQueue.main.async {    self.doSomething()}

Legacy Swift

dispatch_async(dispatch_get_main_queue()) {    self.doSomething()}


There's a saying in software that adding a layer of indirection will fix almost anything.

Have the doSomething method be an indirection shell that only does a performSelectorOnMainThread to call the really_doSomething method to do the actual Something work. Or, if you don't want to change your doSomething method, have the mock test unit call a doSomething_redirect_shell method to do something similar.


Here is a better way to do this in Swift:

runThisInMainThread { () -> Void in    // Run your code    self.doSomething()}func runThisInMainThread(block: dispatch_block_t) {    dispatch_async(dispatch_get_main_queue(), block)}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions