【问题标题】:NSTimer jumping 2 secondsNSTimer 跳跃 2 秒
【发布时间】:2014-04-29 00:43:08
【问题描述】:

请帮忙,

我有一个 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。

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

谢谢。

【问题讨论】:

  • 添加一个NSLog( @"hello" ); 作为timerFireMethod 的第一行,让我们看看你得到了什么。
  • 我添加了一个 NSLog 来查看 secondsLeft 和 timeElapsed 的值,它们似乎减少得很好。但是每行 NSLog 每秒都会出现两个。我希望我知道原因:D
  • 我最好的猜测是您有两个正在运行的计时器实例。尝试将 NSLog 放在 [NSTimer scheduledTimerWithTimeInterval 行之前。
  • 您最好的猜测是正确的 :) 谢谢先生! Apple 提供的包含 configureView 的代码被调用了两次,所以它不是放置我的计时器的最佳位置。如果您回答我的问题,我会将其标记为正确的。

标签: objective-c ios7 nstimer nstimeinterval


【解决方案1】:

我最好的猜测是您有两个正在运行的计时器实例。尝试将 NSLog 放在 [NSTimer scheduledTimerWithTimeInterval 行之前。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    相关资源
    最近更新 更多