我想同步异步方法调用及其委托调用。
例如:
foo 在完成带有结果的操作后调用 bar 。
//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;
}
我需要同步 foo 和 bar 的执行。这样的事情(没有修改 foo )。
-(bool) perform_foo_bar {
int result = [myObj foo_bar:param1:one param2:two]
if (result == 1)
{
return true;
}
else
{
return false;
}
}
是否可以使用大型中央调度(GCD)例程来实现这一目标?
答案 0 :(得分:0)
你的问题很模糊,所以我为你提供了一个通用的解决方案,让你了解如何使用GCD
同步多个线程。我希望它对您有所帮助,您可以在真实的代码中插入这个想法。
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.");
});