【问题标题】:Why is app crashing when showing UIAlertView?为什么显示 UIAlertView 时应用程序崩溃?
【发布时间】:2013-01-02 16:06:45
【问题描述】:

我在处理所有服务器请求的方法中实现了可达性功能。我可以通过 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;
}

【问题讨论】:

  • 您能否至少发布整个标题所指的“功能”?希望看到更多代码——也许还有更清晰的描述。
  • 完成。虽然我认为这对额外的部分没有太大帮助......这个想法是为了让我能够在不导致程序崩溃的情况下显示 UIAlertView。有没有办法“暂停”应用程序,直到警报框被解除?或者我应该有一个完全不同的方法来解决这个问题?
  • 你的代码是否甚至可以用那个空返回来编译? [警报显示] 之后的声明?应该返回一些东西,因为编译器正在寻找你返回一个(id)。
  • 我的错。一些实验的剩菜...现在删除!
  • 关于你的“暂停”问题——我不确定你的代码的其余部分是做什么的,但如果你在后台发生了一些异步请求,那么尝试管理一个暂停主线程和后台线程。我建议尝试通过 (1) 识别可能涉及的所有元素,然后 (2) 对每个元素进行某种 NSLog 测试以排除任何不是的东西,从而缩小崩溃的原因。您会惊讶于以这种方式找到罪魁祸首的速度之快。

标签: iphone objective-c uialertview


【解决方案1】:

将讨论移至聊天后,我们发现您的 UIAlertView 是从后台线程调用的。永远不要在后台线程中做任何与更新 UI(User-Interface)相关的事情。 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];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 2012-11-19
    • 2018-04-03
    • 2013-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多