我在几秒钟后添加了一个关闭UIAlertView
的函数。整个代码如下:
- (void)netWorkAlert
{
UIAlertView *netWork = [[UIAlertView alloc] initWithTitle:@"error" message:@"network has problems" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
[netWork show];
[self performSelector:@selector(dismissAlert:) withObject:netWork afterDelay:2];
}
- (void)dismissAlert:(UIAlertView *)alert
{
if(alert)
{
[alert dismissWithClickedButtonIndex:0 animated:YES];
[alert release];
}
}
当网络不可用时调用netWorkAlert
。
现在我遇到的问题是第二次调用netWorkAlert
时,应用程序被破坏,Xcode显示错误
int main(int argc, char *argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([ZJAppDelegate class]));
//Thread 1 :EXC_BAD_ACCESS(code=1,address=xc0000004)
}
}
我没有使用ARC,我不知道为什么会崩溃。即使我对[alert release];
发表评论,它仍然会在第二次出现同样的问题。
有人可以帮我查一下吗? 谢谢!
答案 0 :(得分:1)
EXC_BAD_ACCESS是由访问已发布的对象引起的。为了避免这种情况,请调用UIAlertView类型的模式:
功能体:
-(void)checkSaving
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Do you want to add these results to your database?"
message:@"\n\n"
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"Save", nil];
alert.alertViewStyle = UIAlertViewStyleDefault;
[alert show];
//this prevent the ARC to clean up :
NSRunLoop *rl = [NSRunLoop currentRunLoop];
NSDate *d;
d= (NSDate*)[d init];
while ([alert isVisible]) {
[rl runUntilDate:d];
}
}
您的选择结果:
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 1)//Save
{
//do something
}
if (buttonIndex == 0)//NO
{
//do something
}
}
在接口声明中注册函数:
@interface yourViewController ()
-(void)checkSaving
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
//...
@end
致电: [self checkSaving];
我希望这会对你有帮助。
答案 1 :(得分:0)
在调用dismissAlert
方法时,UIAlertView可能超出范围(对alert
nil
的检查会阻止此代码崩溃。但是,有一个更好的方法实现这一点的方法alert
永远不会超出范围。
定义networkAlert
方法的类应该实现<UIAlertViewDelegate>
协议。下面的代码允许您拦截用户单击“取消”按钮并执行自定义操作。按取消的默认操作是关闭UIAlertView
。
@interface YourClassName : UIViewController <UIAlertViewDelegate> {}
@implementation YourClassName
-(void) networkAlert
{
UIAlertView *netWork = [[UIAlertView alloc] initWithTitle:@"error"
message:@"network has problems"
delegate:self
cancelButtonTitle:@"cancel"
otherButtonTitles:nil];
[netWork show];
}
- (void) alertViewCancel:(UIAlertView*)alertView
{
what ever it is you want to do when the cancel button is pressed here
}