我如何暂停和恢复我的NSTimer

时间:2015-07-24 13:47:22

标签: ios objective-c iphone ios8 nstimer

我有一个已经有效的NSTimer,但是当你点击一个按钮时想暂停它。除了暂停之外,此按钮会将我重定向到我的其他视图,然后当我回到主视图时,他必须继续从您离开的位置继续。我已经有了暂停按钮,我打算继续计算在viewWillAppear上调用方法

这是我的代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUp];
}

- (void) setUp {
    _startDate = [NSDate date];
    _timer = [NSTimer scheduledTimerWithTimeInterval: 1.0/100.0 target: self selector: @selector(timerUpdating) userInfo: nil repeats: true];
}

-(void)timerUpdating {

    NSDate *currentDate = [NSDate date];
    NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:_startDate];
    NSDate *timerDate  = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc]init];
    [dateFormater setDateFormat:@"mm:ss"];
    [dateFormater setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
    NSString *timeString = [dateFormater stringFromDate:timerDate];
    self.timerLabel.text = timeString;
    self.pauseTimeInterval = &(timeInterval);
}

- (IBAction)timerActionPause:(id)sender {
}

1 个答案:

答案 0 :(得分:0)

- (void)startTimer {
    if(_timer != nil) { // To make sure 
        [self stopTimer];
    }
    _timer = [NSTimer scheduledTimerWithTimeInterval: 1.0/100.0 target: self selector: @selector(timerUpdating) userInfo: nil repeats: true];
}

- (void)stopTimer {
    [_timer invalidate];
    _timer = nil;
}

- (void)resetTimer {
    [self stopTimer];
    [self startTimer];
}