temporizador pro poner for descargar como iphone objective-c xcode nstimer

iphone - pro - spotify sleep timer android



Cómo detener NSTimer (7)

Como iCoder dice que tiene que ser invalidado en viewWillDisappear.

Agregué lo siguiente solo para asegurarme. esto funciona para mi. Espero que ayude (y agrega a la respuesta de los icoders no intente copiar)

- (void) startTimer { [self stopTimer]; timer = [NSTimer scheduledTimerWithTimeInterval: 5.0 target: self selector:@selector(onTick) userInfo: nil repeats:YES]; } - (void) stopTimer { if (timer) { [timer invalidate]; timer = nil; } }

Hola, solo estoy haciendo una aplicación de ejemplo y estoy teniendo un pequeño problema, así que tengo una vista de tabla y luego tengo unas cuantas filas y cuando un usuario hace clic en una fila, las lleva a una nueva vista. En esta vista, tengo un botón para reproducir música. Estoy usando un temporizador para aumentar la barra deslizadora en función de la duración de la música y el tiempo restante.

Ahora mi problema es, ¿qué tengo que poner para que cuando regrese a la vista de tabla a través del botón superior izquierdo, se detenga el NSTimer?

esto es lo que tengo hasta ahora, no puedo obtener una repetición: SÍ, el cronómetro se detiene.

#import "SecondViewController.h" @implementation SecondViewController @synthesize lbl1; @synthesize timer; -(IBAction) slide { myMusic.currentTime = slider.value; } -(IBAction)play { timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateTime) userInfo:nil repeats:YES]; slider.maximumValue = [myMusic duration]; myMusic.volume = 0.2; [myMusic prepareToPlay]; [myMusic play]; } -(IBAction)pause { [myMusic pause]; } -(IBAction)stop { slider.value = 0; myMusic.currentTime = 0; [myMusic stop]; } - (void)updateTime{ slider.value = myMusic.currentTime; } // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { //This plays music, we must give it a path to find the file and then u can change it. NSString * pathToMusicFile = [[NSBundle mainBundle] pathForResource:@"Katy" ofType:@"mp3"]; myMusic = [[ AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:pathToMusicFile] error:NULL]; myMusic.delegate = self; myMusic.numberOfLoops = -1; slider.value = 0; //[myMusic play]; [super viewDidLoad]; } - (void)viewDidUnload { [timer invalidate]; timer = nil; //myMusic.currentTime = 0; [myMusic stop]; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; } -(IBAction) TxtChange;{ lbl1.text = @" test2! I CHNAGED TEXT FROM ANOTHER XIB"; } - (void)dealloc { [timer invalidate]; timer = nil; [myMusic release]; [super dealloc]; } @end


El truco es usar una clase singleton, la clase google myGlobals que se usa principalmente como singleton. Aunque si deseas usar NSTimer , entonces

digamos que la vista 1 es la que entra y la vista 2 es la que retrocede 2.

Entonces, en el caso de la vista 2, escriba NSTimer para invalidar el temporizador en viewDidLoad (suponiendo que tenga dos clases separadas para ambas vistas). Se producirá un problema porque cuando vaya a ver 1, la vista 2 Timers será dealloc. Por lo tanto, haga una clase Singleton y guarde el puntero NSTimer como este

//to be done in viewDidLoad function theGlobals *globals = [theGlobals alloc] init];// for the singleton class to initiate, [globals.myTimer invalidate]; //to be done in viewDidUnload theGlobals *globals = [theGlobals alloc] init];// for the singleton class to initiate, globals.myTimer = [NSTimer scheduledTimerWithTimeInterval: 5.0 target: self selector:@selector(onTick) userInfo: nil repeats:YES];

oh, y aquí está el código de clase myGlobals que necesitarás

//theglobals.h file #import <Foundation/Foundation.h> @interface theGlobals : NSObject { NSTimer *myTimer; } @property (nonatomic, copy) NSString *changeyes; +(theGlobals*)sharedInstance; @end //implementaton .m file #import "theGlobals.h" @implementation theGlobals @synthesize myTimer; static theGlobals *sharedInstance; - (id) init { return self; } +(theGlobals*)sharedInstance { if (!sharedInstance) { sharedInstance = [[theGlobals alloc] init]; } return sharedInstance; } @end


Me gusta esto:

[yourtimername invalidate];

Pero ten cuidado, no puedes detener el cronómetro si ya está parado porque tu aplicación fallará.


Podría usar dos cosas diferentes

[timername invalidate];

O podrías usar

timername = nil;


Publicación de 4 años, lo sé, pero quizás pueda salvar al chico NEXT de perder tiempo intentando invalidar un NSTimer. La documentación de las manzanas lo explica y funciona para mí.

en .h

@property(nonatomic, retain) NSTimer *yourTimer; @property(weak) NSTimer *repeatingTimer;

En m

@synthesize yourTimer, repeatingTimer;

en viewDidLoad

yourTimer = [NSTimer scheduledTimerWithTimeInterval:(NSTimerInterval)(40.0/60.0) target:self selector:@selector(blink) userInfo:nil repeats:TRUE]; self.repeatingTimer = yourTimer;

en mi opinión, DiDisappear

[repeatingTimer invalidate]; repeatingTimer = nil;

el truco está en la asignación del primer NSTimer al objeto NStimer (débil) y matar ese objeto.


Solo invalide el temporizador

[timer invalidate];


Usa el siguiente código Funcionará Pero tenga en cuenta que solo se debe invocar si nuestro temporizador está en modo ejecución, de lo contrario la aplicación se bloqueará.

- (void)viewWillDisappear:(BOOL)animated { //BEFORE DOING SO CHECK THAT TIMER MUST NOT BE ALREADY INVALIDATED //Always nil your timer after invalidating so that //it does not cause crash due to duplicate invalidate if(timer) { [timer invalidate]; timer = nil; } [super viewWillDisappear:animated]; }