2012-08-22 28 views
0

我已經啓動了一個計時器,在10秒後調用一個方法。計時器從didFinishLaunchingWithOptions開始。它工作正常,但我想在註銷時停止另一個UISubclass的計時器。我該怎麼做我的代碼是停止NSTimer從應用程序運行didFinishLaunchingWithOptions

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    [NSThread sleepForTimeInterval:2.0]; 

    [self.window addSubview:viewController.view]; 
    [self setupTimer]; 
    [self.window makeKeyAndVisible]; 

    return YES; 
} 
-(void)setupTimer; 
{ 
    timer = [NSTimer timerWithTimeInterval:10 
            target:self 
            selector:@selector(triggerTimer:) 
            userInfo:nil 
            repeats:YES]; 
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; 
} 

-(void)triggerTimer:(NSTimer*)timer; 
{ 
    NSLog(@"===============this method is call after every 10   second==========================="); 
    Getlocation *object=[[Getlocation alloc] init]; 
    [object updatelocation]; 
} 
    -(void)stopTimer:(NSTimer*)timer; 
{ 
    [timer invalidate]; 
    timer=nil; 
} 

回答

0
if([timer isValid]) 
    [timer invalidate]; 

timer = nil; 
0

採取的NSTimer的對象。
寫這行要撥打

timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(NEWTIMER) userInfo:nil repeats:YES]; 

方法寫這個代碼中有你想停止計時器在哪裏。

[timer invalidate]; 
timer = nil; 
[timer release]; 
如果你想停止計時,當你的應用程序來的背景。你應該寫這個代碼到這個方法

- (void)applicationWillEnterForeground:(UIApplication *)application 
{ 
    [timer invalidate]; 
    timer = nil; 
    [timer release]; 
} 
+0

:感謝您的答覆,但我註銷登錄觀點出現後,這一次我不想執行的計時器任務,之後註銷。 –

0

在註銷ButtonAction方法中編寫代碼。

- (IBAction爲)LogOutButtonPressed:(ID)發送方{

[計時器無效];定時器=零; [定時發佈];

}

+0

但我從這裏在didFinishLaunchingWithOptions中創建了我的計時器,如果您看到代碼,則會調用此計時器。 –