计时器(销毁后的时间也计算)

计时器思想:
1. 开始计时, 存储计时器失效时间戳到本地
2. 视图消失, 计时器失效
3. 视图出现, 取出时间戳与当前时间戳对比: 大于当前时间戳说明计时超时, 否则创建计时器
4. 计时开始 == 按钮失效; 计时过期 == 按钮可用

- (void)showTime {
    //如果 时间间隔 小于0: 计时器停止, 按钮重新可用
    if (self.timeInterval-- <= 0) {
        [self.timer invalidate];
        self.startButton.enabled = YES;
        self.showTimeLabel.text = @"过期";

    } else {
        /*
         两种不同的输出格式: a. 全部显示秒 b. 分钟: 秒
         */
        //self.showTimeLabel.text = [NSString stringWithFormat:@"%ld", self.timeInterval];
        self.showTimeLabel.text = [NSString stringWithFormat:@"%ld:%.2ld", self.timeInterval/60, self.timeInterval%60];
    }

}

- (void)viewWillAppear:(BOOL)animated {
    //每次视图出现时, 先取得当前时间戳与最终时间戳比较
    NSDate *now = [NSDate date];
    NSTimeInterval nowInterval = [now timeIntervalSince1970];
    NSInteger endInterval = [[NSUserDefaults standardUserDefaults] integerForKey:@"end"];
    NSInteger margin = nowInterval - endInterval;

    //如果小于0, 说明计时器未过期, 创建计时器, 计时开始
    if (margin <= 0) {
        self.startButton.enabled = NO;
        //重新设置 显示的剩余时间
        self.timeInterval = -margin;
        self.showTimeLabel.text = [NSString stringWithFormat:@"%ld:%.2ld", self.timeInterval/60, self.timeInterval%60];
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];

}

- (void)viewDidDisappear:(BOOL)animated {
    if (self.timer.valid) {
        [self.timer invalidate];
    }
}

//开始计时
- (IBAction)startTime:(id)sender {
    //70s后的时间戳, 存储到本地
    NSDate *now = [NSDate date];
    NSDate *nextTime = [NSDate dateWithTimeInterval:ktotalTime sinceDate:now];
    NSTimeInterval nextInterval = [nextTime timeIntervalSince1970];
    [[NSUserDefaults standardUserDefaults] setInteger:nextInterval forKey:@"end"];

    //计时开始
    self.timeInterval = ktotalTime;
    if (!self.timer.valid) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];
        self.startButton.enabled = NO;
    }
}

版权声明:本文为zhz459880251原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。