2011-11-27 54 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 
} 
相關問題