Accuracy of NSTimer

后端 未结 4 1347
时光取名叫无心
时光取名叫无心 2020-12-03 12:59

I am trying to use NSTimer to create a Stop-watch style timer that increments every 0.1 seconds, but it seems to be running too fast sometimes ..

This is how I\'ve

4条回答
  •  清歌不尽
    2020-12-03 13:34

    Here's a class you can use to do what you want:

    @interface StopWatch()
    @property ( nonatomic, strong ) NSTimer * displayTimer ;
    @property ( nonatomic ) CFAbsoluteTime startTime ;
    @end
    
    @implementation StopWatch
    
    -(void)dealloc
    {
        [ self.displayTimer invalidate ] ;
    }
    
    -(void)startTimer
    {
        self.startTime = CFAbsoluteTimeGetCurrent() ;
        self.displayTimer = [ NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector( timerFired: ) userInfo:nil repeats:YES ] ;
    }
    
    -(void)stopTimer
    {
        [ self.displayTimer invalidate ] ;
        self.displayTimer = nil ;
    
        CFAbsoluteTime elapsedTime = CFAbsoluteTimeGetCurrent() - self.startTime ;
        [ self updateDisplay:elapsedTime ] ;
    }
    
    -(void)timerFired:(NSTimer*)timer
    {
        CFAbsoluteTime elapsedTime = CFAbsoluteTimeGetCurrent() - self.startTime ;
        [ self updateDisplay:elapsedTime ] ;
    }
    
    -(void)updateDisplay:(CFAbsoluteTime)elapsedTime
    {
        // update your label here
    }
    
    @end
    

    The key points are:

    1. do your timing by saving the system time when the stop watch is started into a variable.
    2. when the the stop watch is stopped, calculate the elapsed time by subtracting the stop watch start time from the current time
    3. update your display using your timer. It doesn't matter if your timer is accurate or not for this. If you are trying to guarantee display updates at least every 0.1s, you can try setting your timer interval to 1/2 the minimum update time (0.05s).

提交回复
热议问题