Question

Please help,

I have a NSTimeInterval which I convert into a NSDateComponent and then assign each component (year, month, day, etc) to an appropriate label. After I do the conversion I start an NSTimer to begin a countdown. Here's the code I use:

- (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 and secondsLeft are all NSTimeIntervals.

For some reason the label jumps two seconds instead of just one. I have no idea why this is happening. Any ideas?

Thank you.

Was it helpful?

Solution

My best guess is that you have two instances of the timer running. Try putting an NSLog ahead of the [NSTimer scheduledTimerWithTimeInterval line.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top