2011-11-16 114 views
0

我用的NSTimer一起使用NSThread。的NSTimer scheduledTimerWithTimeInterval:重复:NO选择方法调用多次

我的代码是这样的

-(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; 

} 

现在的问题是,我alertbox来两次在 startTimerForRecentAlarm 方法一个呼叫。所以警报来了两次,我的看法卡住了。

这里会出现什么问题?

我想实现使用单一的NSTimer有多个报警选项报警。

请帮助。

当调试这一点,我可以找到很多并发线程对同一代码(UIAlertView中)上运行。

回答

1

我看不到任何明显的原因,那被称为两次,但它似乎是在做你需要做的事情有一个过于复杂的方式。

你有没有想过使用local notifications

如果你不想这样做,你可以重构你的代码,所以它的工作原理是这样的: 1.添加一个新事件 2.如果没有计时器或事件的时间少于时间在计时器上,然后为此事件设置计时器。 3.当计时器触发时,检查下一个事件并为该事件设置一个计时器(如果有的话)。

+0

谢谢您的回复。请给我一些代码块,以便我可以实现相同的逻辑。 –

1

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

如果你有多个线程做UIAlertView中,你有另外一个问题,因为你只能(可靠)在主线程做UI。

+0

谢谢你的回复。你能不能建议一些代码,以便我可以用较简单的方法来做到这一点。请因为我是iPhone应用程序开发的新手。 –

+0

我没有编码本地通知,但他们似乎是完成警报的最佳方式。 (当你的应用程序没有运行时,他们可以做些什么。)或者,如果你有n个不同的警报,创建n个不同的NSTimers。我看不到只需要使用一个计时器。底线,避免线程,除非你绝对需要它们,因为线程代码总是很难得到正确的。 –

+0

其实我试图实现从互联网流媒体作为我的警报音。我有以下假设,如果我错了,请纠正我..... 1)本地通知 - 当alertbox出现时,用户必须点击按钮打开应用程序并播放流。但对我来说,它应该自动播放。 2)n个不同的NSTimers会减慢应用程序UI导航。 3)没有线程时,应用程序用户界面只是在Timer启动时卡住。 –