【问题标题】:Order of executing methods执行方法的顺序
【发布时间】:2014-05-07 13:04:53
【问题描述】:

我对执行方法的顺序有疑问。

if (indexPath.row == 2) {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:@"Data will be downloaded"
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];

    if([app getData]){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                        message:@"Data is downloaded."
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
    }   
}

当我运行这段代码 sn-p 时,我想首先显示一个警报视图。但是,它会在显示警报视图之前调用getData 方法。一旦getData方法完成,alertView就来到了窗口。

我该如何纠正这个问题?

【问题讨论】:

  • [alert show]; 被异步调用。这就是为什么它立即调用[app getData]

标签: ios methods uialertview


【解决方案1】:

该函数是异步调用的,因此 appData 在第一个警报视图可见之前被调用。将您的代码更改为:

if (indexPath.row == 2) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                message:@"Data will be downloaded"
                                               delegate:self
                                      cancelButtonTitle:@"OK"
                                      otherButtonTitles:nil];
[alert show];

} 当用户在您的第一个警报上按 OK 时将调用以下方法,但这意味着当第一个警报可见时,您的 appData 代码不会启动。

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([app getData]){
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:@"Data is downloaded."
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
}   

}

注意:记得在你的视图控制器中添加 UIAlertViewDelegate

【讨论】:

    【解决方案2】:

    我没有 Xcode,但无论如何我都会尝试一下。您的问题是因为在主循环迭代之前不会显示警报。并且在您的 getData 方法执行之前它不会迭代,因为您是在主线程上执行此操作的。所以你需要分叉。

    尝试将您的 if() 包装成这样:

    dispatch_async(dispatch_get_main_queue(),
    ^ {
        if([app getData]){
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                        message:@"Data is downloaded."
                                                       delegate:self
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
            [alert show];
        }   
    });
    

    【讨论】:

    • 它拯救了我的一天。谢谢。
    【解决方案3】:

    这是因为运行循环必须继续运行,所以[UIAlertView show] 是异步的,不会阻塞当前线程。如果主线程被阻塞,则无法传递用户界面事件。

    如果您希望在第一个警报视图关闭后发生某些事情,请在 alertView:clickedButtonAtIndex: 委托方法中执行。

    【讨论】:

      最近更新 更多