ios 将函数移动到目标 c 中的后台线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12671042/
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
moving a function to a background thread in objective c
提问by MoKaM
I have a function that returns a string that takes 15 seconds to compute on an iPhone.
我有一个函数,它返回一个字符串,在 iPhone 上计算需要 15 秒。
I want to be able to run the function on the background thread so that the main thread can be used for the user interface.
我希望能够在后台线程上运行该函数,以便主线程可用于用户界面。
I've heard GCD
is a new technology that is good for this, can someone provide some example code in regards to how this would work?
我听说GCD
有一种新技术对此很有用,有人可以提供一些关于它如何工作的示例代码吗?
That is to run a generic function on the background thread and return the result to a UI text field.
即在后台线程上运行通用函数并将结果返回到 UI 文本字段。
EDIT:
编辑:
Thanks Alladinian it works a treat.
感谢 Alladinian,它很有用。
However, when I use GCD my function takes 1 second longer to execute on the iphone simulator (I'd guess this'd be about 5 seconds on an iphone (ill have to test it later today to be sure))
但是,当我使用 GCD 时,我的函数在 iphone 模拟器上执行需要 1 秒的时间(我猜这在 iphone 上大约需要 5 秒(我今天晚些时候必须测试以确保))
Is there any reason why this is? Perhaps the background thread is slower or something?
有什么原因吗?也许后台线程较慢或什么?
回答by Alladinian
Well that's pretty easy actually with GCD. A typical workflow would be something like this:
嗯,实际上使用 GCD 很容易。一个典型的工作流程是这样的:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
dispatch_async(queue, ^{
// Perform async operation
// Call your method/function here
// Example:
NSString *result = [anObject calculateSomething];
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
// Example:
self.myLabel.text = result;
});
});
For more on GCD you can take a look into Apple's documentation here
回答by Trausti Thor
Also to add, sometimes you don't need to use GCD, this one is very simple to use :
另外要补充的是,有时您不需要使用 GCD,这个使用起来非常简单:
[self performSelectorInBackground:@selector(someMethod:) withObject:nil];