Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS Grand Central Dispatch with callback method

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?

like image 661
tg2007 Avatar asked Oct 29 '12 03:10

tg2007


1 Answers

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.

like image 115
matt Avatar answered Oct 24 '22 11:10

matt