Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop NSTimer started on button click in this timer callback method

I am having problems with stoping NSTimer started on button click. [timer invalidate] and timer = nil; just do nothing neither when I am trying to stop it viewWillDisappear nor in method invoked by method which is being invoked by this timer. However when I start my timer in viewWillAppear and invalidate it in viewWillDisappear everything is fine.

I suppose there might be an issue in thread I am starting the timer from. Can you help with that?

I looked through all answers here regarding NSTimer not stopping, but they didn't help to solve the problem.

The way I initialize my timer:

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

The ways I tried to stop it:

[self.timer invalidate];
[timer invalidate];
like image 745
Roman Minenok Avatar asked Feb 12 '26 05:02

Roman Minenok


2 Answers

It's funny how quick you can answer your own question after you asked for a help. No matter how long you have been struggling to find the answer before by yourself:

[self performSelectorOnMainThread:@selector(stopTimer) withObject:nil waitUntilDone:YES];

And the selector:

- (void) stopTimer
{
    [timer invalidate];
    timer = nil;
}
like image 116
Roman Minenok Avatar answered Feb 14 '26 17:02

Roman Minenok


I have created and tested this:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    myTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(oneSecondPassedSinceRoundStarted:) userInfo:nil repeats:YES];
}

-(void)oneSecondPassedSinceRoundStarted:(NSTimer *)time {
    // Do what You want

    NSLog(@"CALLING!");
}

-(IBAction)buttonAction:(id)sender {

    NSLog(@"Stop timer!");

    [myTimer invalidate];
    myTimer = nil;
}

And it is working nice.

Note: You forget to add colon after oneSecondPassedSinceRoundStarted.

like image 45
Justin Boo Avatar answered Feb 14 '26 17:02

Justin Boo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!