Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone UIAlertView Modal

Is it possible to present a UIAlertView and not continue executing the rest of the code in that method until the user responds to the alert?

Thanks in advance.

like image 869
ghiboz Avatar asked Nov 22 '10 17:11

ghiboz


2 Answers

I guess stopping the code you meant was to stop the device to run the next code you have written after the alertview

For that just remove your code after your alertview and put that code in the alertview delegate

-(void) yourFunction
{
     //Some code
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:@"Your Message" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
            [alert show];
            [alert release];
     //Remove all your code from here put it in the delegate of alertview
}
-(void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:    (NSInteger)buttonIndex 
{
if(buttonIndex==0)
    {
        //Code that will run after you press ok button 
    }
}

Dont forget to include UIAlertViewDelegate in the .h file

like image 55
ipraba Avatar answered Sep 20 '22 01:09

ipraba


An answer has already been accepted, but I'll note for anyone who comes across this question that, while you shouldn't use this for normal alert handling, in certain circumstances you may want to prevent the current execution path from continuing while an alert is being presented. To do so, you can spin in the run loop for the main thread.

I use this approach to handle fatal errors which I want to present to the user before crashing. In such a case, something catastrophic has happened, so I don't want to return from the method that caused the error which might allow other code to be executed with an invalid state and, for example, corrupt data.

Note that this won't prevent events from being processed or block other threads from running, but since we're presenting an alert which essentially takes over the interface, events should generally be limited to that alert.

// Present a message to the user and crash
-(void)crashNicely {

  // create an alert
  UIAlertView *alert = ...;

  // become the alert delegate
  alert.delegate = self;

  // display your alert first
  [alert show];

  // spin in the run loop forever, your alert delegate will still be invoked
  while(TRUE) [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantFuture]];

  // this line will never be reached
  NSLog(@"Don't run me, and don't return.");

}

// Alert view delegate
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
  abort(); // crash here
}
like image 33
BWW Avatar answered Sep 18 '22 01:09

BWW