2010-12-15 67 views
2

我試圖在我的應用進入後臺時使計時器無效。當您點擊一個啓動計時器的按鈕並在TimerController.m文件中時,計時器會被調用。這是如何被調用的。現在在進入後臺時使NSTimer無效

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]; 

,我想,當應用進入後臺無效mytimer,所以我試圖把 [mytimer無效]。 進入 - (void)applicationDidEnterBackground:(UIApplication *)應用程序方法的應用程序委託。但是由於它在代表中未聲明,所以這不起作用。我認爲通過將TimerController.h納入委託,這將工作,但它不會。

所以,我顯然不知道我在這裏做什麼。你能幫我嗎?它是如何得到它,讓應用程序進入後臺時mytimer失效?

回答

11

還有一個UIApplicationDidEnterBackgroundNotification通知當應用程序進入後臺時發佈。您可以認購您的控制器此通知和處理存在的過渡:

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

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

Great..that works..thanks – Allen 2010-12-15 16:35:50

0
if (timer) { 
     [timer invalidate]; 
     timer = nil; 
    } 
在applicationReEnteredForeground通知方法

還將努力