我希望调度组内的代码在发生任何事情之前完成执行,实质上阻止应用程序执行任何操作,直到完成此代码。但是,我无法让调度组阻止运行中的其他代码。我已经在堆栈上尝试了几乎所有的建议,但我不知道我在做什么。调度组不阻止代码运行
我的功能:
- (void)myFunction {
NSString *myString = @"Hello world";
dispatch_group_t group = dispatch_group_create();
NSLog(@"1 entering the dispatch group");
dispatch_group_enter(group);
[self doSomething:myString completion:^{
dispatch_group_leave(group);
NSLog(@"2 we have left the dispatch group");
}];
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"3 notifying that the dispatch group is finished");
}];
NSLog(@"4 all process are complete, we are done");
}
我通过日志语句要输出= 1,2,3,4
输出I通过日志语句得到= 1,4,2,3
为什么我的代码跳过调度组并在2和3之前打印4?任何关于我在做什么错误的建议表示赞赏。谢谢!
更新:
这是我doSomething
方法。我的代码不断挂在dismiss
呼叫。
doSomething() {
viewController.dismiss(animated: false completion: { [weak self] in
doMoreCode()
})
}
感谢您的回应!我用dispatch_group_wait''得到的问题是它保持死锁。有什么办法解决这个问题,或者只是暂停一下? – user3353890
我喜欢使用'''dispatch_group_wait''',因为在继续之前我需要确保doSomething''完成,但它对我保持死锁。它只是挂起,所以我将不得不调查为什么会发生。 – user3353890
@ user3353890您的死锁,因为'dispatch_group_leave'必须从与dispatch_group_wait不同的线程调用。不知道doSomething实际上做了什么,很难确定。用更多的细节更新你的问题。 – rmaddy