NSTimer scheduledTimerWithTimeInterval:重复:NO选择器方法多次调用

时间:2011-11-16 18:10:11

标签: iphone nstimer uialertview nsthread

我正在使用NSThread和NSTimer。

我的代码就像这样

-(void) checkForRecentAlarm
{
    if ([self.alarmThread isFinished]) 
     {
        [self.alarmThread cancel];
     }
    self.alarmThread = [[NSThread alloc] initWithTarget:self selector:@selector(startTimerForRecentAlarm) object:nil];
    [self.alarmThread start];
    //[NSThread detachNewThreadSelector:@selector(startTimerForRecentAlarm) toTarget:self withObject:nil];
}
-(void)startTimerForRecentAlarm
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
    self.recentAlarmTime = [NSDate date];
    self.dbObject = [[RADataBaseModelManager alloc] init];
    self.recentAlarmTime = [self.dbObject getMostRecentAlarmTimeFromDB];
    if (self.recentAlarmTime) {
        NSTimeInterval timeIntervalToAlarm = [self.recentAlarmTime timeIntervalSinceNow];
        NSRunLoop* runLoop = [NSRunLoop currentRunLoop];
         //Fire timer every second to updated countdown and date/time
        self.RATimer = [NSTimer scheduledTimerWithTimeInterval:timeIntervalToAlarm target:self selector:@selector(timerFireMethod:) userInfo:nil repeats:NO];
        [runLoop run];
    }
    [pool release];
}
 - (void)timerFireMethod:(NSTimer*)theTimer
{
    [self.RATimer invalidate];
    [theTimer invalidate];
    self.RATimer = NULL;
    theTimer = NULL;
    [self playAlarm];
    UIAlertView *alarmAlert = [[UIAlertView alloc] initWithTitle:@"Alarm" message:@"" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:@"Snooze", nil]; 
    [alarmAlert show];
    [alarmAlert release];
    alarmAlert = nil;

}

现在的问题是,我的警报箱来了两次     startTimerForRecentAlarm 方法。因此,警报会两次出现,我的观点会被卡住。

这会有什么问题?

我正在尝试使用单个NSTimer实现具有多个警报选项的警报。

请帮忙。

当我调试它时,我可以发现许多同时线程正在相同的代码上运行(UIAlertView)。

2 个答案:

答案 0 :(得分:1)

我看不出任何明显的原因,为什么会被调用两次,但它似乎是一种过于复杂的方式来做你需要做的事情。

您是否考虑过使用local notifications

如果您不想这样做,您可以重构代码,使其工作方式如下: 1.添加新活动 2.如果没有计时器或事件的时间短于计时器的时间,则为此事件设置计时器。 3.当计时器触发时,检查下一个事件并为该事件设置计时器(如果有)。

答案 1 :(得分:1)

这看起来确实很复杂。我的一般观察是,如果你得到两个计时器,那是因为你出于某种原因有两个计时器。

如果您有多个线程正在执行UIAlertView,则还有另一个问题,因为您只能(可靠地)从主线程执行UI。