如何在 Objective-C 中等待线程完成 [英] How to wait for a thread to finish in Objective-C
本文介绍了如何在 Objective-C 中等待线程完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用从某处下载的类中的方法.该方法在后台执行,同时程序继续执行.在此方法完成之前,我不想让程序继续执行.我该怎么做?
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?
推荐答案
这是使用 GCD 的另一种方法:
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
}
这篇关于如何在 Objective-C 中等待线程完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文