等待Objective-C中的异步操作

Sea*_*ess 3 asynchronous objective-c grand-central-dispatch ios

我谷歌搜索疯狂,仍然对此感到困惑.

我想将一个文件URL数组下载到磁盘,我想根据下载时每个文件加载的字节更新我的视图.我已经有了下载文件的东西,并通过块报告进度和完成情况.

如何为阵列中的每个文件执行此操作?

我可以一次做一个.我可以通过这种方式轻松计算总进度:

float progress = (numCompletedFiles + (currentDownloadedBytes / currentTotalBytes)) / totalFiles)
Run Code Online (Sandbox Code Playgroud)

我主要理解GCD和NSOperations,但是如何告诉操作或dispatch_async块在完成之前等待回调?似乎有可能通过覆盖NSOperation,但这似乎有点矫枉过正.还有另外一种方法吗?只有GCD才有可能吗?

Wol*_*urs 16

我不确定我是否理解正确,但也许你需要派遣信号量来实现你的目标.在我的一个项目中,我使用调度信号量等待另一个玩家完成另一个转弯.这部分是我使用的代码.

for (int i = 0; i < _players.count; i++)
{

    // a semaphore is used to prevent execution until the asynchronous task is completed ...

    dispatch_semaphore_t sema = dispatch_semaphore_create(0);


    // player chooses a card - once card is chosen, animate choice by moving card to center of board ...

    [self.currentPlayer playCardWithPlayedCards:_currentTrick.cards trumpSuit:_trumpSuit completionHandler:^ (WSCard *card) {

        BOOL success = [self.currentTrick addCard:card];

        DLog(@"did add card to trick? %@", success ? @"YES" : @"NO");

        NSString *message = [NSString stringWithFormat:@"Card played by %@", _currentPlayer.name];
        [_messageView setMessage:message];

        [self turnCard:card];
        [self moveCardToCenter:card];


        // send a signal that indicates that this asynchronous task is completed ...

        dispatch_semaphore_signal(sema);

        DLog(@"<<< signal dispatched >>>");
    }];


    // execution is halted, until a signal is received from another thread ...

    DLog(@"<<< wait for signal >>>");

    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    dispatch_release(sema);


    DLog(@"<<< signal received >>>");
Run Code Online (Sandbox Code Playgroud)


das*_*das 7

调度组是GCD工具,用于跟踪一组独立或单独异步的块/任务的完成情况.

使用dispatch_group_async()提交有问题的块,或者在触发异步任务之前使用dispatch_group_enter()组,并在任务完成时使用dispatch_group_leave()组.

然后,当组中的所有块/任务完成时,您可以通过dispatch_group_notify()异步通知,或者如果必须,您可以使用dispatch_group_wait()同步等待完成.