0

我正在尝试向主线程发送 2 个警报视图,但如果第一个警报视图没有被关闭并且第二个出现,则应用程序崩溃。我将如何避免这种情况?

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

1 回答 1

0

将您的 alertView 声明为 ivar 或“ @property”,如果它已经存在,则不要显示下一个警报。

或者关闭第一个警报并调出下一个警报。

例如,当您想调出警报时:

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");
}

当它关闭时,使用委托方法:

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    // setting this to NULL means that another alert can be displayed
    self.alertView = NULL;
}
于 2013-07-06T06:37:14.677 回答