How to wait for a thread to finish in Objective-C

node ninja picture node ninja · Oct 7, 2010 · Viewed 32k times · Source

I'm trying to use a method from a class I downloaded somewhere. The method executes in the background while program execution continues. I do not want to allow program execution to continue until this method finishes. How do I do that?

Answer

jpswain picture jpswain · Nov 23, 2012

Here's another way to do it using GCD:



- (void)main
{
    [self doStuffInOperations];
}

- (void)doStuffInGCD
{
    dispatch_group_t d_group = dispatch_group_create();
    dispatch_queue_t bg_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_group_async(d_group, bg_queue, ^{
        [self doSomething:@"a"];
    });

    dispatch_group_async(d_group, bg_queue, ^{
        [self doSomething:@"b"];
    });

    dispatch_group_async(d_group, bg_queue, ^{
        [self doSomething:@"c"];
    });


    // you can do this to synchronously wait on the current thread:
    dispatch_group_wait(d_group, DISPATCH_TIME_FOREVER);
    dispatch_release(d_group);
    NSLog(@"All background tasks are done!!");


    // ****  OR  ****

    // this if you just want something to happen after those are all done:
    dispatch_group_notify(d_group, dispatch_get_main_queue(), ^{
        dispatch_release(d_group);
        NSLog(@"All background tasks are done!!");        
    });
}

- (void)doSomething:(id)arg
{
    // do whatever you want with the arg here 
}