开发者

Invalidate an NSTimer when going into background

I'm trying to invalidate a timer when my app goes into background. The timer gets invoked when you hit a button that starts the timer and is in the TimerController开发者_运维技巧.m file. Here is how it gets invoked.

    mytimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updateTime) userInfo:nil repeats:YES];//Timer with interval of one second
    [[NSRunLoop mainRunLoop] addTimer:mytimer forMode:NSDefaultRunLoopMode];

Now, I'd like to invalidate mytimer when the app goes into background, so I tried putting [mytimer invalidate]; into the - (void)applicationDidEnterBackground:(UIApplication *)application method the apps delegate. But this won't work since it's undeclared in the delegate. I thought by including TimerController.h into the delegate, this would work, but it won't.

So, I clearly don't know what I'm doing here. Can you help? How do it get it so that mytimer is invalidated when the app goes into background?


There’s also a UIApplicationDidEnterBackgroundNotification notification posted when the application goes into background. You can subscribe for this notification in your controller and handle the transition there:

[[NSNotificationCenter defaultCenter]
    addObserver:self
    selector:@selector(goBackground)
    name:UIApplicationDidEnterBackgroundNotification
    object:nil];

// and later:
- (void) goBackground {
    [timer invalidate], timer = nil;
}


if (timer) {
        [timer invalidate];
        timer = nil;
    }

in applicationReEnteredForeground notification method will also work

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜