2011-11-27 75 views

回答

4

NSDateFormatter仅用于格式化日期,而不是时间间隔。一个更好的方法是记录你启动计时器的时间,并且每秒更新一次标签,从启动计时器开始已经过去了多少时间。

- (void)startTimer { 
    // Initialize timer, with the start date as the userInfo 
    repeatTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateLabel) userInfo:[NSDate date] repeats:YES]; 
} 

- (void)updateLabel:(NSTimer *)timer { 
    // Get the start date, and the time that has passed since 
    NSDate *startDate = (NSDate *)[timer userInfo]; 
    NSTimeInterval timePassed = [[NSDate date] timeIntervalSinceDate:startDate]; 

    // Convert interval in seconds to hours, minutes and seconds 
    int hours = timePassed/(60 * 60); 
    int minutes = (timePassed % (60 * 60))/60; 
    int seconds = ((timePassed % (60 * 60)) % 60); 
    NSString *time = [NSString stringWithFormat:@"%i:%i:%i", hours, minutes, seconds]; 

    // Update the label with time string 
} 
相关问题