将函数移至目标c中的后台线程 [英] moving a function to a background thread in objective c

查看:46
本文介绍了将函数移至目标c中的后台线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数返回一个需要15秒才能在iPhone上进行计算的字符串.

I have a function that returns a string that takes 15 seconds to compute on an iPhone.

我希望能够在后台线程上运行该功能,以便可以将主线程用于用户界面.

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.

我听说GCD是一项新技术,对此很有用,有人可以提供一些示例代码来说明其工作原理吗?

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?

这是在后台线程上运行通用函数,并将结果返回到UI文本字段.

That is to run a generic function on the background thread and return the result to a UI text field.

感谢Alladinian的治疗.

Thanks Alladinian it works a treat.

但是,当我使用GCD时,我的功能在iphone模拟器上执行需要花费1秒以上的时间(我想这在iphone上大约需要5秒钟(请确保今天晚些时候进行测试))

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))

这是什么原因吗?也许后台线程较慢或什么?

Is there any reason why this is? Perhaps the background thread is slower or something?

推荐答案

使用GCD实际上很容易.典型的工作流程如下:

Well that's pretty easy actually with GCD. A typical workflow would be something like this:

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;
    });
});

有关GCD的更多信息,请查看

For more on GCD you can take a look into Apple's documentation here

这篇关于将函数移至目标c中的后台线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆