Search code examples
iphoneobjective-ccocoa-touchios4nstimer

How can I invalidate the timer when timer going in Background?


In my app I used the timer,

When First time start the timer I want to stop that timer when it going in background,

So I used this code to stop the timer,

 - (void)applicationWillEnterForeground:(UIApplication *)application
{
  FirstViewController *view = [[FirstViewController alloc]init];
 [view.myticker invalidate];    //myticker is timer
    view.myticker = nil;
 [view release];
}

I have invalidate the timer when Foreground delegate method call,

But when come to viewcontroller the old timer is still running,

How can i invalidate the timer when timer going in Background?


Solution

  • There is no need to move your timer to your delegate, in fact that is quite a bad idea as it has no purpose being there!

    You should observe the following notifications (depending on OS version, the latter being in OS4+)...

    UIApplicationWillResignActiveNotification UIApplicationDidEnterBackgroundNotification

    Observe these from within your view controller and invalidate the timer. There are corresponding notifications when the app starts again...

    UIApplicationDidBecomeActiveNotification UIApplicationWillEnterForegroundNotification