Xavi Valero
Xavi Valero

Reputation: 2057

Crash when UIAlertView is clicked

When I click the UIAletView, I receive the following error.

alertView:clickedButtonAtIndex:]: message sent to deallocated instance 0x84c7010

This is the code I have used.

    UIAlertView  *testAlert = [[ UIAlertView alloc]initWithTitle:messageTitle message:messageBody delegate:self cancelButtonTitle:messageClose otherButtonTitles:messageTryAgain, nil];
    testAlert.tag = 2;
    [testAlert show];
    [testAlert release];

And I have the delegate method

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

}

When I click the UIAlertView , even before the control reaches the delegate method, the app crashes. What could be the reason. What am I doing wrong?

Upvotes: 2

Views: 1989

Answers (3)

Jesse Black
Jesse Black

Reputation: 7976

This is "one hack of a solution".
Hopefully it helps you understand that your delegate is the memory issue. The delegete (in this case self) is deallocated somehow before the testAlert is dismissed

  // retain self to avoid crash you were experiencing earlier
UIAlertView  *testAlert = [[ UIAlertView alloc]initWithTitle:messageTitle message:messageBody delegate:[self retain] cancelButtonTitle:messageClose otherButtonTitles:messageTryAgain, nil];
testAlert.tag = 2;
[testAlert show];
[testAlert release];


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
  // release self because you've gotten past the crash
  [self release];
}

This is in no way an elegant solution and should encourage you to debug your app further to find out why self is being deallocated prematurely

Upvotes: 8

Amit
Amit

Reputation: 1795

If ARC enable UIAlertView Object retain and no need to release, it's automatically release your object.

Upvotes: 1

Probably Sleepin
Probably Sleepin

Reputation: 165

Just wondering, could you show us your .h file?

If I had to hazard a guess, you've forgotten to set your class to respond to UIAlertViews as a delegate

You might be missing something like this:

@interface MyClass : UIViewController <UIAlertViewDelegate>

Upvotes: 2

Related Questions