Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS: stop a NSTimer [duplicate]

Tags:

xcode

ios

nstimer

Possible Duplicate:
NSTimer doesn't stop

I have this code:

[NSTimer scheduledTimerWithTimeInterval:110.0                                  target:self                                selector:@selector(targetMethod:)                                userInfo:nil                                 repeats:YES];  - (void) targetMethod:(NSTimer) timer{ NSLog(@"Hello World");} 

in targetMethod I can stop timer with [timer invalidate], but out of this method, How can I stop targetMethod?

like image 747
cyclingIsBetter Avatar asked Dec 15 '11 17:12

cyclingIsBetter


2 Answers

You can keep your NSTimer in a variable and stop the timer using the invalidate method. Like the following:

NSTimer * myTimer = [NSTimer scheduledTimerWithTimeInterval:110.0                                  target:self                                selector:@selector(targetMethod:)                                userInfo:nil                                 repeats:YES];  [myTimer invalidate]; 
like image 64
Raphael Petegrosso Avatar answered Oct 15 '22 02:10

Raphael Petegrosso


One way to do it is to create NSTimer *timer; as a global variable so you can have a handle to the timer. Some thing likes this:

NSTimer *timer;  //global var  timer = [NSTimer scheduledTimerWithTimeInterval:110.0                                  target:self                                selector:@selector(targetMethod:)                                userInfo:nil                                 repeats:YES]; 

To stop timer somewhere in the same class:

[timer invalidate]; 
like image 25
user523234 Avatar answered Oct 15 '22 04:10

user523234