Search code examples
iphoneobjective-ccrashalertterminate

Adding An AlertView At viewWillAppear, iPhone


I am attempting to show an alert view as soon as the view appears (without using a button). In viewcontroller.m I have:

- (void) viewWillAppear:(BOOL)animated
{
    UIAlertView *alert = [[UIAlertView alloc]
initWithTitle: @"User Information" message: @"Hello"
                              delegate: self cancelButtonTitle:nil otherButtonTitles: @"Continue", nil];

    [alert show];

    [alert release];
}

and in viewcontroller.h I have:

IBOutlet UIView *alert; 

I haven't done anything to my .xib file.

When run on the simulator I get the following in console:

2009-11-30 23:41:36.079 BatteryApp[867:20b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIViewController _loadViewFromNibNamed:bundle:] loaded the "BatteryAppViewController" nib but the view outlet was not set.'

Any ideas where I have gone wrong, something to do with my xib?

Edit // I connect alert to a new view in my xib, still no luck


Solution

  • The problem is that the two core animations (the one for viewing the current view, and the one for showing the alert ) overlap. You need to separate these two animation moves, by following this workaround:

    1. Have the alert code be in viewDidAppear, rather than viewWillAppear

    2. Call [alert performSelector:@selector(show) withObject:nil afterDelay:0.0]. This ensures that the alert occurs after finishing the current animation.

    You may need to be careful about releasing alert quite yet. If I were you, I would have a separate method (e.g. showHelloAlert), and then call it from viewDidAppear:

    - (void)viewDidAppear: (BOOL)animated {
      [self performSelector:@selector(showHello) withObject:nil afterDelay:0.0f];
      [super viewDidAppear:animated];
    }