IOS Grand Central Dispatch with callback method

吃可爱长大的小学妹 提交于 2020-01-01 09:14:30

问题


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.

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

    });


}

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?


回答1:


You're spot on; that's the standard pattern for getting off and on the main thread. See my answer here: https://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

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.



来源:https://stackoverflow.com/questions/13115657/ios-grand-central-dispatch-with-callback-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!