2012-04-23 22 views
5

Estoy tratando de implementar la lógica de reintento con retroceso exponencial usando NSTimer. Mi código es el siguiente:Uso de NSTimer para implementar la lógica de reintento con retroceso exponencial

-(void)start 
{ 
    [NSTimer scheduledTimerWithTimeInterval:0.0 target:self 
    selector:@selector(startWithTimer:) userInfo:nil repeats:NO]; 
} 

-(void)startWithTimer:(NSTimer *)timer 
{ 
    if (!data.ready) { 
    // timer.timeInterval == 0.0 ALWAYS! 
    NSTimeInterval newInterval = timer.timeInterval >= 0.1 ? timer.timeInterval * 2 : 0.1; 
    newInterval = MIN(60.0, newInterval); 
    NSLog(@"Data provider not ready. Will try again in %f seconds.", newInterval); 
    NSTimer * startTimer = [NSTimer scheduledTimerWithTimeInterval:newInterval target:self 
     selector:@selector(startWithTimer:) userInfo:nil repeats:NO]; 
    // startTimer.timeInteval == 0.0 ALWAYS! 
    return; 
    } 

    ... 
} 

El problema que estoy teniendo es que el temporizador NSTimer scheduledTimerWithTimeInterval parece ignorar el intervalo que estoy proporcionando y siempre lo establece en 0,0. ¿Alguna sugerencia sobre lo que estoy haciendo mal aquí?

Respuesta

5

La documentación de Apple tiene esto que decir sobre la propiedad timeInterval en NSTimer.

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/nstimer_Class/Reference/NSTimer.html

Si el receptor es un temporizador que no se repite, devuelve 0 (incluso si se estableció un intervalo de tiempo).

Tendrá que utilizar algún otro medio para realizar un seguimiento de lo que debe ser el intervalo del temporizador. Recomiendo un iVar en tu clase.

-(void)start 
{ 
    _timeInterval = 0.0; 
    [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self 
    selector:@selector(startWithTimer:) userInfo:nil repeats:NO]; 
} 

-(void)startWithTimer:(NSTimer *)timer 
{ 
    if (!data.ready) { 
    _timeInterval = _timeInterval >= 0.1 ? _timeInterval * 2 : 0.1; 
    _timeInterval = MIN(60.0, _timeInterval); 
    NSLog(@"Data provider not ready. Will try again in %f seconds.", _timeInterval); 
    NSTimer * startTimer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval target:self 
     selector:@selector(startWithTimer:) userInfo:nil repeats:NO]; 
    return; 
    } 

    ... 
} 
+0

¡Gracias! Creo que debería leer los documentos la próxima vez. :) – Ivan

Cuestiones relacionadas