1

我想在一个dispatch_group_asyc块中执行一些网络调用时显示一个活动指示器。但活动指示器仅在块完成时显示。我正在创建一个dispatch_group_t,因为我需要在执行其他一些任务之前获得网络调用的结果。这是我的代码的简化版本:

- (BOOL)doNetCall
{
  [activityIndicator startAnimating];

  __block BOOL netResult = NO;

  dispatch_queue_t queue = dispatch_queue_create(netQueue, NULL);
  dispatch_group_t group = dispatch_group_create();
  dispatch_group_async(group,queue,^{
    netResult = [service queryService];
  });

  dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
  dispatch_release(group);
  dispatch_release(queue);

  [activityIndicator stopAnimating];

  if (netResult) {  
    // Perform some tasks
  }
  else {
    [self showAlertView];
  }

  return netResult;
}

我究竟做错了什么?谢谢!

编辑:我需要该方法等到块完成才能返回我得到的结果

4

2 回答 2

4

您应该以这种方式使用活动指示器:

[activityIndicator startAnimating];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    // Do something...
    dispatch_async(dispatch_get_main_queue(), ^{
        [activityIndicator stopAnimating];
    });
});

如果您正在使用group,只需稍微重写您的代码。

于 2013-07-03T15:15:00.673 回答
0

似乎不需要与您正在做的事情的调度组。尝试这个:

- (void)buttonClicked {
    [activityIndicator startAnimating];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL netResult = [service queryService];

        dispatch_async(dispatch_get_main_queue(), ^{
            [activityIndicator stopAnimating];

            if (netResult) {
                // perform some tasks
            } else {
                // show alert
            }
        });
    });
}

如果您有队列,请将呼叫替换为dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)您自己的队列。

于 2013-07-03T15:13:26.823 回答