objective-c - 如何在 Objective-C 中等待线程完成

标签 objective-c multithreading cocoa-touch background nsthread

我正在尝试使用从某处下载的类中的方法。该方法在后台执行,而程序继续执行。在该方法完成之前,我不想让程序继续执行。我该怎么做?

最佳答案

这是使用 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 - 如何在 Objective-C 中等待线程完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3879034/

相关文章:

ios - 使用添加为 subview 的按钮自动调整 TableView 单元格

iPhone TCP 连接

objective-c - 使用presentModalViewController时如何更改UINavigationVIewController

vb.net - 关于Multithread-.Net的问题

c# - 每x秒同时启动几个功能吗?

具有 2 个线程的 C++ 队列

swift - UITableViewCell 属性在设置属性的某些方式期间不会显示在 View 上

iphone - 时间间隔自日期问题

objective-c - NSSortDescriptor - 按位置排序

iphone - iPhone 开发的卷页和翻页效果