IOS中央调度与回调方法 [英] IOS Grand Central Dispatch with callback method

查看:187
本文介绍了IOS中央调度与回调方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有在我的应用程序中使用GCD或大量线程,但我遇到了一种情况,我需要运行一个方法或两个线程。一旦这个方法完成,我需要调用另一个方法使用主线程从回调。我一直在寻找,看看如何检测线程何时完成操作,但仍然不太清楚的主题。

I haven't used GCD or much threading in my apps but I've run into a situation where I need to run a method or two off another thread. Once this method completes I need to call another method using the main thread from a callback. I've been searching around to see how to detect when a thread has finished the operation but still not too clear on the subject.

我创建了一个测试应用程序,只是使用viewDidLoad方法作为一个快速示例。

I created a test app and just used the viewDidLoad method for a quick example.

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        NSLog(@"viewDidLoad called");
        sleep(5);  // simulating a thread being tied up for 5 seconds


        dispatch_async(dispatch_get_main_queue(), ^{
            [self callbackMethod];  // method called after above thread has completed running
        });

    });


}

m试图做什么?当运行应用程序时,看起来在sleep(5)完成后调用回调方法。

Will this example work for what I'm trying to do? When running the application it appears that the callback method is called after the sleep(5) finishes. Is this the proper way of handling this situation or am I way off course?

推荐答案

这是正确的方法来处理这种情况,这是下线和主线程的标准模式。请参阅我的答案: http://stackoverflow.com/a/13080519/341994

You're spot on; that's the standard pattern for getting off and on the main thread. See my answer here: http://stackoverflow.com/a/13080519/341994

例如我的书中的代码,结构如下:

And for example code from my book, structured in this very way:

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch25p868mandelbrotGCD /ch38p1106mandelbrotNoThreading/MyMandelbrotView.swift

在该示例中,查看 drawThatPuppy 如何从主线程做耗时的计算,然后回到主线程上去绘图进入界面。

In that example, look at how drawThatPuppy gets off the main thread to do the time-consuming calculations and then back on the main thread to do the drawing into the interface.

这篇关于IOS中央调度与回调方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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