开发者

Alternative to NSTimer

Is there any other alternative other than using NSTimer. I got CFRunLoopTimer but not able to get it working.

The reason why i am searching for an alternative is that in my code even if i invalidate the timer it's still firing.My code is something like this


-(void)SetTimerTo:(NSInteger)timePeriod
{
    self.alarmTimer=[NSTimer scheduledTimerWithTimeInterval: timePeriod
                                                       target: self
                                                     selector: @selector(TimerFired)
                                                     userInfo: nil
                                                      repeats: NO]; 
}

-(void)StopTimer { [self.alarmTimer invalidate]; self.alarmTimer=nil; }

-(void开发者_如何学编程)TimerFired { //Show alarm expired. //Check if any other alarms are scheduled.If any again set the alarm.

}

-(void)UpdateTimerTo:(NSInteger)timePeriod { if([self.alarmTimer IsValid]) { [self.alarmTimer invalidate]; } self.alarmTimer=[NSTimer scheduledTimerWithTimeInterval:timePeriod target: self selector:@selector(TimerFired) userInfo: nil repeats: NO]; } -(void)DeleteAlarm { [self StopTimer]; }

The problem is that if i update time greater than the previously set time, then also the timer is firing at the old time only. Please help I'm stuck with this....


As I don't see any obvious mistakes in the code you posted:

Are you — by any chance — setting up and tearing down your timers within varying runloop contexts, like on different threads?
That would totally explain the behaviour you describe.

Another thing you might want to consider, is providing your own setter for the alarmTimer property, where you invalidate the old timer before letting go of it and keeping the new one. That would rule out the possibility that you re-set the property somewhere else and hence can't reach the old one to invalidate.


try call

[self.alarmTimer isValid];

(lower case "i").
Besides, instead of scheduling another timer, you may consider to update just the timer fire date, calling [self.alarmTimer setFireDate:];. It may be less expensive if you update frequently your fire date. If you wish to "invalidate" the timer for a while you may call

[self.alarmTimer setFireDate:[NSDate distantFuture]];

this way the timer is active but never fires.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜