NSTimer跳2秒

时间:2014-04-29 00:43:08

标签: objective-c ios7 nstimer nstimeinterval

请帮忙,

我有一个NSTimeInterval,我将其转换为NSDateComponent,然后将每个组件(年,月,日等)分配给适当的标签。在我进行转换后,我启动NSTimer开始倒计时。这是我使用的代码:

- (void)configureView
{
    if (self.detailItem) {
        self.progressView.progress = 0.0;
        self.initialInterval = [[self.detailItem valueForKey:@"date"] timeIntervalSinceNow];
        self.timeElapsed = self.initialInterval;
        self.secondsLeft = [self resetLabel];
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1
                                                          target:self
                                                        selector:@selector(timerFireMethod:)
                                                        userInfo:nil
                                                         repeats:YES];
    }
}

- (void)timerFireMethod:(NSTimer *)timer
{
    if (self.secondsLeft > 0) {
        self.secondsLeft--;
        self.timeElapsed--;
        [self updateSecondsWithNumber:self.secondsLeft];
        self.progressView.progress = 1 - (self.timeElapsed / self.initialInterval);
    } else {
        if (self.timeElapsed <= 0) { [timer invalidate]; return; }
        [self resetLabel];
        self.secondsLeft = 59;
    }
}

- (void)updateSecondsWithNumber:(int)number
{
    self.secondLabel.text = [NSString stringWithFormat:@"%ds", number];
}

- (NSTimeInterval)resetLabel
{
    NSDateComponents *convertedInfo = [ChronoModel dateComponentFromTimeInterval:self.timeElapsed];
    self.yearLabel.text = [NSString stringWithFormat:@"%ldy", (long)convertedInfo.year];
    self.monthLabel.text = [NSString stringWithFormat:@"%ldm", (long)convertedInfo.month];
    self.dayLabel.text = [NSString stringWithFormat:@"%ldd", (long)convertedInfo.day];
    self.hourLabel.text = [NSString stringWithFormat:@"%ldh", (long)convertedInfo.hour];
    self.minuteLabel.text = [NSString stringWithFormat:@"%ldm", (long)convertedInfo.minute];
    self.secondLabel.text = [NSString stringWithFormat:@"%lds", (long)convertedInfo.second];
    return convertedInfo.second;
}

timeElapsed,initialInterval和secondsLeft都是NSTimeIntervals。

由于某种原因,标签跳了两秒而不是一秒。我不知道为什么会这样。有什么想法吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

我最好的猜测是你有两个计时器运行实例。尝试将NSLog置于[NSTimer scheduledTimerWithTimeInterval行之前。