2011-12-15 8 views
26

Duplicar posibles:
NSTimer doesn't stopIOS: detener una NSTimer

tengo este código:

[NSTimer scheduledTimerWithTimeInterval:110.0 
           target:self 
           selector:@selector(targetMethod:) 
           userInfo:nil 
           repeats:YES]; 

- (void) targetMethod:(NSTimer) timer{ 
NSLog(@"Hello World");} 

en targetMethod puedo dejar de temporizador con [invalidate temporizador], pero fuera de este método, ¿cómo puedo detener TargetMethod?

Respuesta

69

Usted puede mantener su NSTimer en una variable y detener el temporizador usando el método invalidate. Como el siguiente:

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

[myTimer invalidate]; 
16

Una forma de hacerlo es crear el temporizador NSTimer *; como una variable global para que pueda controlar el temporizador. Algo le gusta esto:

NSTimer *timer; //global var 

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

Para detener el temporizador en algún lugar de la misma clase:

[timer invalidate];