当显示UIAlertView时,为什么应用程序崩溃?

3

我已经在处理所有服务器请求的方法中实现了可达性功能。我可以通过NSLogs清楚地看到该函数完美地运行。然而,该方法从未有过"暂停",这意味着我无法使用UIAlertView而不崩溃程序。

也许我正在完全错误的方向上处理,但我找不到其他解决方法......

有人有想法如何以某种方式显示通知吗?

提前感谢

代码:

-(id) getJson:(NSString *)stringurl{
Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];

NSLog(@"reached %d", reach.isReachable);

if (reach.isReachable == NO) {

   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Passwords don't match."
     message:@"The passwords did not match. Please try again."
     delegate:nil
     cancelButtonTitle:@"OK"
     otherButtonTitles:nil];
     [alert show];

}else{
    id x =[self getJsonFromHttp:stringurl];
    return x;
}
return nil;
}

你能否至少发布标题所指的“函数”的完整代码呢?想看更多代码 - 也许有一个更清晰的描述。 - eric
虽然我不认为这会对额外的部分有太大帮助...但是我的想法是以某种方式使我能够在不崩溃程序的情况下显示UIAlertView。是否有一种方法可以“暂停”应用程序,直到警报框被解除?或者我应该采用完全不同的方法来解决这个问题? - Tom
我的错。是一些实验的残留物...已经删除了! - Tom
关于你的“暂停”问题--我不确定你的代码的其余部分是什么,但如果你有一些异步请求在后台发生,那么尝试管理主线程和后台线程的暂停将会是一个头痛的任务。我建议尝试通过(1)识别可能涉及的所有元素,然后(2)对每个元素进行某种 NSLog 测试来缩小崩溃原因。你会惊讶地发现,用这种方式很快就能找到罪魁祸首。 - eric
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/22074/discussion-between-eric-and-user1534948 - eric
显示剩余2条评论
1个回答

2

将讨论移到聊天中后,我们发现您的UIAlertView是从后台线程调用的。永远不要在后台线程中执行任何与更新UI(用户界面)相关的操作。UIAlertView通过添加一个小弹出对话框来更新UI,因此应该在主线程上完成。修复方法如下:

// (1) Create a new method in your .m/.h and move your UIAlertView code to it
-(void)showMyAlert{ 

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Passwords don't match." 
                           message:@"The passwords did not match. Please try again." 
                           delegate:nil 
                               cancelButtonTitle:@"OK" 
                           otherButtonTitles:nil]; 
    [alert show]; 

}

// (2) In -(id)getJson replace your original UI-related code with a call to your new method
[self performSelectorOnMainThread:@selector(showMyAlert)
                             withObject:nil
                          waitUntilDone:YES];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接