views:

173

answers:

2

HI , i have made simple application with 5 view controllers with some functionality .. what i want to do now is add a time at the main screen . and it should b running till i quit from application .. i will move to other view controllers also but that timer would b running .. how i will have this functionality ??

+3  A: 

Check out the "Timers" section here: http://www.iphoneexamples.com/

Also, refer to Apple's NSTimer Documentation

fbrereto
A: 

The most practical way to do this is to fake it - that is, just store the start timestamp, and don't bother to continuously maintain any kind of timePassed variable. This is both easier to code, and actually more reliable since it's stable.

Store an NSDate for the instant the timer was started, and whenever you want to display or update the timer, use NSDate's timeIntervalSinceNow method, which returns the number of seconds passed as an NSTimeInterval, which is basically a typedef for a double. Note: this function returns a negative number when called on a timestamp in the past, which will be the case here.

If part of your display is showing this time, you can update it every second (or even more often) with an NSTimer object that periodically called one of your methods which updates the display.

Sample code:

// In the initialization code:
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self
              selector:@selector(secondPassed:) userInfo:nil repeats:YES];

// Later:
// (This code assumes #minutes < 60.)
- (void) secondPassed: (NSTimer:) timer {
    NSTimeInterval secondsPassed = -1 * [self.timerStart timeIntervalSinceNow];
    int minutes = (int)(secondsPassed / 60);
    int seconds = (int)(seconds - minutes * 60);
    NSString* timerString = [NSString stringWithFormat:@"%02d:%02d",
                             minutes, seconds];
    [self updateTimerDisplay:timerString];
}
Tyler