scheduledtimer example create ios timer nstimer

ios - example - NSTimer timerWithTimeInterval: no funciona



timer swift 4 (4)

Creé una aplicación de prueba con temporizador antes de implementarlo en mi proyecto. Fue la primera vez que uso temporizador. Pero el problema es cuando implementé el temporizador usando [NSTimer timerWithTimeInterval: target: selector: userInfo: repeats: ]; , no está trabajando. Aquí está mi código, Interfaz:

@interface uialertViewController : UIViewController { NSTimer *timer; } -(void)displayAlert; -(void)hideandview; @end

Implementación:

@implementation uialertViewController - (void)viewDidLoad { [self displayAlert]; [super viewDidLoad]; } -(void)displayAlert{ timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(hideandview) userInfo:nil repeats:NO]; alert = [[UIAlertView alloc] initWithTitle:@"testing" message:@"hi hi hi" delegate:nil cancelButtonTitle:@"continue" otherButtonTitles:nil]; [alert show]; [alert release]; alert = nil; } -(void)hideandview{ NSLog(@"triggered"); [alert dismissWithClickedButtonIndex:0 animated:YES]; [alert release]; [self displayAlert]; } @end

Luego [NSTimer timerWithTimeInterval: target: selector: userInfo: repeats: ]; con [NSTimer scheduledTimerWithTimeInterval: target: selector:userInfo: repeats: ]; , Está funcionando . ¿Cuál fue el problema con timerWithTimeInterval: :? ¿Estoy malinterpretando algo en mi primera implementación? Gracias por adelantado.


Como respuesta anterior notó el horario en el hilo principal, pero en lugar de usar assert, colóquelo en el hilo principal:

@objc func update() { ... } DispatchQueue.main.async { self.timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) }

Y si no se desea la asincronía, intente esto:

let schedule = { self.timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.update), userInfo: nil, repeats: true) } if Thread.isMainThread { schedule() } else { DispatchQueue.main.sync { schedule() } }


La diferencia entre los dos es que el método timerWithTimeInterval devuelve un objeto NSTimer que aún no se ha NSTimer . Para disparar el temporizador, debe usar [timer fire]; Por otro lado, scheduledTimerWithTimeInterval devuelve un NSTimer que ya ha sido disparado.

Entonces, en tu primera implementación, estabas perdiendo [timer fire];


También es posible que desee asegurarse de agregar temporizador en el hilo principal.

assert(Thread.isMainThread) let timer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(YourSelector), userInfo: nil, repeats: true)


scheduledTimerWithTimeInterval:invocation:repeats: and scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: crea temporizadores que se agregan automáticamente a un NSRunLoop , lo que significa que no tienes que agregarlos tú mismo. NSRunLoop agregados a un NSRunLoop es lo que hace que disparen.

Con timerWithTimeInterval:invocation:repeats: and timerWithTimeInterval:target:selector:userInfo:repeats: tiene que agregar el temporizador a un ciclo de ejecución manualmente, con un código como este:

[[NSRunLoop mainRunLoop] addTimer:repeatingTimer forMode:NSDefaultRunLoopMode];

Otras respuestas aquí sugieren que debes llamar al fire tú mismo. No lo haga; se lo llamará tan pronto como el temporizador se haya puesto en un ciclo de ejecución.