Objective-C : NSTimer and countdown

后端 未结 2 955
甜味超标
甜味超标 2020-12-09 23:44

I know that I should understand Apple\'s documentation for NSTimer, but I don\'t! I have also read a lot of questions about it but can not find one that suites my case. Well

2条回答
  •  半阙折子戏
    2020-12-10 00:10

    First you should calculate what your countdown time is, in seconds and put it in a instance variable (ivar)

    NSTimeInterval totalCountdownInterval;
    

    I think in order to keep good accuracy (NSTimer firing can be off by as much as 100ms and errors will add up) you should record the date at which the countdown started, and put it in another ivar:

    NSDate* startDate = [NSDate date];
    

    Then you can have a timer firing at regular (here 1 second) intervals calling a method on your class repeatedly

    NSTimer* timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkCountdown:) userInfo:nil repeats:YES];
    

    And in that method you check the elapsed time against the total countdown time and update the interface

    -(void) checkCountdown:(NSTimer*)_timer {
    
        NSTimeInterval elapsedTime = [[NSDate date] timeIntervalSinceDate:startDate];
    
        NSTimeInterval remainingTime = totalCountdownInterval - elapsedTime;
    
        if (remainingTime <= 0.0) {
            [_timer invalidate];
        }
    
        /* update the interface by converting remainingTime (which is in seconds)
           to seconds, minutes, hours */
    
    }
    

提交回复
热议问题