Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Add two observers for when app enter in background and for app enterForeGround</p> <pre><code>[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterInBackGround) name:UIApplicationWillResignActiveNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterInForeground) name:UIApplicationWillEnterForegroundNotification object:nil]; - (void)applicationWillEnterInBackGround{ // stop your timer here } - (void)applicationWillEnterInForeground { // start your timer here } </code></pre> <p>Example ------</p> <p>in .h</p> <pre><code>NSTimer *timer; float time; </code></pre> <p>in .m</p> <pre><code>- (void)viewDidLoad { [super viewDidLoad]; timer=[NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterInBackGround) name:UIApplicationWillResignActiveNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterInForeground) name:UIApplicationWillEnterForegroundNotification object:nil]; } - (void)applicationWillEnterInBackGround { [timer invalidate]; } - (void)applicationWillEnterInForeground { timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(stopwatch) userInfo:nil repeats:YES]; } - (void)stopwatch // Start counting the stopwatch { hourInt = [hourLabel.text intValue]; // Store integer values of time minuteInt = [minuteLabel.text intValue]; secondInt = [secondLabel.text intValue]; if (secondInt == 59) { // Add on one second secondInt = 0; if (minuteInt == 59) { minuteInt = 0; if (hourInt == 23) { hourInt = 0; } else { hourInt += 1; } } else { minuteInt += 1; } } else { secondInt += 1; } NSString *hourString = [NSString stringWithFormat:@"%02d", hourInt]; // Update text to show time NSString *minuteString = [NSString stringWithFormat:@"%02d", minuteInt]; NSString *secondString = [NSString stringWithFormat:@"%02d", secondInt]; hourLabel.text = hourString; minuteLabel.text = minuteString; secondLabel.text = secondString; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload