Calling a method on the main thread?

别等时光非礼了梦想. 提交于 2019-11-28 16:17:43
aryaxt

Objective-C

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

Swift

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

Swift 3 and 4

DispatchQueue.main.async {
   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

RomOne

And now in Swift 3:

DispatchQueue.main.async{
   self.doSomething()
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!