为什么在显示UIAlertView时应用程序崩溃?
问题描述:
我已经在处理所有服务器请求的方法中实现了Reachability功能。我可以通过NSLog看到该函数完美工作。但是在方法中从来没有“暂停”,这意味着我不能在不崩溃程序的情况下使用UIAlertView。为什么在显示UIAlertView时应用程序崩溃?
我可能在这个可以去完全错误的方式,但我无法找到任何东西...
有谁知道如何获得通知以某种方式表明的想法?
在此先感谢
CODE:
-(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中正在从后台线程调用。切勿在后台线程中更新与更新UI(用户界面)相关的任何内容。 UIAlertView通过添加一个弹出式对话框来更新用户界面,因此它应该在主线程上完成。通过进行以下更改来修复:
// (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];
您能否至少发布标题引用的“函数”的全部内容?希望看到更多的代码 - 也许更清晰的描述。 – sean
完成。虽然我不认为这会对额外的部分产生太大的帮助......但这个想法是让我能够在没有程序崩溃的情况下显示UIAlertView。有没有办法“暂停”应用程序,直到警报框被解除?或者我应该对问题采取完全不同的方法? – Tom
你的代码是否用那个空的return来编译? [alert show]后的声明?应该返回一些东西,因为编译器正在寻找你返回一个(id)。 – sean