Search code examples
objective-cgrand-central-dispatchnsnotificationcenternsnotification

Dispatch group and NSNotification


My issue is simple. I have 3 tasks, one is triggered by an NSNotification. How to I wait for all task to be completed before proceeding.

So far, I tried using dispatch group but can't find a way to add the task triggered by NSNotification. (I tried adding the dispatch command within the method triggered by the NSNotification, but if the notification comes after task 1 and 2, it's too late to add to the group as it is already completed.)

_asyncDispatch = dispatch_group_create();


dispatch_group_async(_asyncDispatch,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    [self doTask1];
});

dispatch_group_async(_asyncDispatch,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
    [self doTask2];
});

dispatch_group_notify(_asyncDispatch,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {

    // We're done!
});

Solution

  • Thanks @Sega-Zero for your guidance. Here is the solution I implemented.

    _operationQueue = [[NSOperationQueue alloc] init];
    _semaphore = dispatch_semaphore_create(0);
    
    NSOperation *uploadOperation = [NSBlockOperation blockOperationWithBlock:^{
        [self doFirstTask];
    }];
    
    NSOperation *downloadOperation = [NSBlockOperation blockOperationWithBlock:^{
        dispatch_semaphore_wait(_semaphore, DISPATCH_TIME_FOREVER);
    }];
    NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
        [self doNextMethod];
    }];
    
    [completionOperation addDependency:uploadOperation];
    [completionOperation addDependency:downloadOperation];
    
    [_operationQueue addOperations:@[uploadOperation, downloadOperation, completionOperation] waitUntilFinished:NO];
    

    And then, in the method triggered by the NSNotification

    -(void)methodTriggeredByNotif:(NSNotification *)notification {
    
    // doing some serious stuff here and when done
    dispatch_semaphore_signal(_semaphore);}
    

    Voila. Thanks to all.