UIAlertview exc_bad_access

我添加了一个函数来closuresUIAlertView几秒钟后。整个代码是这样的:

 - (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]; } } 

networking不可用时调用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]; ,第二次还是有同样的问题。

任何人都可以帮我检查一下吗? 谢谢!

在调用dismissAlert方法的时候,UIAlertView可能会超出范围(检查alert是否为nil可以防止代码崩溃,但是有一个更好的方法可以实现这一点,即alert不会超出范围。

定义networkAlert方法的类应实现<UIAlertViewDelegate>协议。 下面的代码允许您拦截用户点击“取消”button并执行自定义操作。 按取消的默认操作是closuresUIAlertView

@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 } 

EXC_BAD_ACCESS是由访问释放的对象引起的。 为了避免这种情况,您可以调用UIAlertViewtypes的模式:

function体:

 -(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]; } } 

您的select结果:

 - (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];

我希望这会帮助你。