问题描述:

I want to synchronize an async method call and its delegate call.

For example:

Below foo calls bar after it completes the operation with a result.

//foo is an aync method..resides somewhere in external lib

[myObj foo:self action:@selector(bar:) param1:one param2:two];

// delegate

- (void) bar: (int) value {

// Do something with the int result

int result = value;

}

I need to synchronize the execution of both foo and bar. something like this (without modifying foo).

-(bool) perform_foo_bar {

int result = [myObj foo_bar:param1:one param2:two]

if (result == 1)

{

return true;

}

else

{

return false;

}

}

Is it possible to achieve this using grand central dispatch(GCD) routines?

网友答案:

your question is quite ambiguous, so I provide a generic solution for you about how you can synchronise multiple threads with the GCD. I hope it helps on you and you can insert the idea in your real code.

dispatch_group_t _group = dispatch_group_create();

dispatch_group_async(_group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"procedure 1, a long runtime is being simulated in 5 secs, but you can put anything here instead.");
    [NSThread sleepForTimeInterval:5.f];
    NSLog(@"procedure 1 is done...");
});

dispatch_group_async(_group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"procedure 2, a longer runtime is being simulated in 10 secs, but you can put anything here instead.");
    [NSThread sleepForTimeInterval:10.f];
    NSLog(@"procedure 2 is done...");
});

dispatch_group_notify(_group, dispatch_get_main_queue(), ^{
    NSLog(@"both procedures have been done.");
});
相关阅读:
Top