在返回之前等待完成async-part

时间:2013-12-30 12:17:45

标签: ios xcode asynchronous grand-central-dispatch

我在尝试阻止我的连接方法在整个连接部分完成之前退出时遇到问题。

在连接过程中,我显示progress spinner

如何确定仅在整个连接块完成后调用“return ret”。

我使用NSCondition进行了尝试,如此处所示(How do I return from a getter of an asynchronous property?),但没有成功......

她是我代码的一部分:

MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:vC.view animated:YES];
hud.labelText = [NSString stringWithFormat: NSLocalizedString(@"login_to_server", @"")];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {

    //Try to connect

    // If OK
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        [MBProgressHUD hideHUDForView:vC.view animated:YES];            
    });

    // If NOK
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        [alert show]; // Showing UIAlertView with error message
    });       
});
return ret;}

1 个答案:

答案 0 :(得分:0)

你做不到。为了解决您的问题,您通常会有一个完成块,一旦完成异步作业,就会调用它。

调用异步方法可以这样做:

[_activityIndicatorView startAnimating];
[self doSomeAsynchronousWork:^(BOOL success) {
    [_activityIndicatorView stopAnimating];
}];

doSomeAsynchronousWork:看起来像这样:

- (void)doSomeAsynchronousWork:(void (^)(BOOL success))completionBlock {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // do some work and call the completion block once finished
        dispatch_async(dispatch_get_main_queue(), ^{
            completionBlock(YES);
        });
    });
}