ios 在主线程上调用方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5606145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a method on the main thread?
提问by aryaxt
First of all I am writing code for iphone.
I need to be able to call a method on the main thread without using performSelectorOnMainThread
.
The reason that I don't want to use performSelectorOnMainThread
is that it causes problem when I am trying to create a mock for unit testing.
首先,我正在为 iphone 编写代码。我需要能够在不使用performSelectorOnMainThread
. 我不想使用的performSelectorOnMainThread
原因是当我尝试为单元测试创建模拟时它会导致问题。
[self performSelectorOnMainThread:@Selector(doSomething) withObject:nil];
The problem is that my mock knows how to call doSomething
but it doesn't know how to call performSelectorOnMainThread
.
问题是我的模拟知道如何调用doSomething
但它不知道如何调用performSelectorOnMainThread
.
So Any solution?
所以有什么解决办法吗?
回答by aryaxt
Objective-C
目标-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()
}
回答by hotpaw2
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.
让 doSomething 方法成为一个间接 shell,它只执行 performSelectorOnMainThread 来调用 real_doSomething 方法来完成实际的 Something 工作。或者,如果您不想更改 doSomething 方法,请让模拟测试单元调用 doSomething_redirect_shell 方法来执行类似操作。
回答by Esqarrouth
Here is a better way to do this in Swift:
这是在 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
它作为标准函数包含在我的 repo 中,请查看:https: //github.com/goktugyil/EZSwiftExtensions
回答by RomOne
And now in Swift 3:
现在在 Swift 3 中:
DispatchQueue.main.async{
self.doSomething()
}
回答by Muhammad Zeeshan
// Draw Line
func drawPath(from polyStr: String){
DispatchQueue.main.async {
let path = GMSPath(fromEncodedPath: polyStr)
let polyline = GMSPolyline(path: path)
polyline.strokeWidth = 3.0
polyline.strokeColor = #colorLiteral(red: 0.05098039216, green: 0.5764705882, blue: 0.2784313725, alpha: 1)
polyline.map = self.mapVu // Google MapView
}
}