IOS Grand Central Dispatch采用回调方式

时间:2022-03-24 09:01:39

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.

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

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

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

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

    });


}

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?

这个例子是否适用于我正在尝试做的事情?运行应用程序时,似乎在sleep(5)完成后调用了回调方法。这是处理这种情况的正确方法还是我离开了?

1 个解决方案

#1


6  

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

你被发现了;这是下线和主线程的标准模式。请在此处查看我的答案:https://*.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

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.

在该示例中,查看drawThatPuppy如何离开主线程以执行耗时的计算,然后返回主线程以进行绘制到接口。

#1


6  

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

你被发现了;这是下线和主线程的标准模式。请在此处查看我的答案:https://*.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

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.

在该示例中,查看drawThatPuppy如何离开主线程以执行耗时的计算,然后返回主线程以进行绘制到接口。