0

I'm trying to send 2 alert views to the main thread but if the first alert view has not been dismissed and the second shows up, the application crashes. how would i avoid this?

- (void)viewDidLoad
{
    [super viewDidLoad];
    gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        self.date1 = [NSDate dateWithTimeInterval:[testTask timeInterval] sinceDate:[NSDate date]];

        timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction:) userInfo:nil repeats:YES];
        [timer fire];
}
-(void)timerAction:(NSTimer *)t{
     NSDate *now = [NSDate date];
    NSDateComponents *components = [gregorianCalendar components:NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit  fromDate:now toDate:self.date1 options:0];

    NSString *timeRemaining = nil;
    if([now compare:self.date1] == NSOrderedAscending){
        timeRemaining = [NSString stringWithFormat:@"%02d:%02d:%02d", [components hour], [components minute], [components second]];
        NSLog(@"works %@", timeRemaining);
    } else {
        timeRemaining = [NSString stringWithFormat:@"00:00:00"];
        [self.timer invalidate];
        self.timer = nil;
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:[testTask taskName] message:@"Time is up!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];       
        NSLog(@"ended");
    }
   timerLabel.text = timeRemaining;
    [timerLabel setNeedsDisplay];
    [self.view setNeedsDisplay];
}
EvilAegis
  • 733
  • 1
  • 9
  • 18

1 Answers1

0

Declare your alertView as an ivar or a "@property" and if it already exists, don't display the next alert.

Or dismiss the first alert and bring up the next one.

For example, when you want to bring up the alert:

if(self.alertView == NULL)
{
    self.alertView = [[UIAlertView alloc]initWithTitle:[testTask taskName] message:@"Time is up!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];       
    NSLog(@"ended");
}

And when it dismisses, use the delegate method:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    // setting this to NULL means that another alert can be displayed
    self.alertView = NULL;
}
Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • thanks for answering, that solved the problem. but do you know why the application crashes when i press ok and dismiss the alert? – EvilAegis Jul 07 '13 at 17:54