2012-04-23 23 views
5

Tôi đang cố gắng thực hiện thử lại logic với việc trả về theo hàm mũ bằng NSTimer. Mã của tôi trông như thế này:Sử dụng NSTimer để thực hiện thử lại logic với backoff theo hàm mũ

-(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; 
    } 

    ... 
} 

Vấn đề tôi đang gặp là bộ đếm thời gian NSTimer scheduledTimerWithTimeInterval dường như bỏ qua những khoảng thời gian tôi đang cung cấp và luôn đặt nó để 0.0. Bất kỳ đề xuất về những gì tôi đang làm sai ở đây?

Trả lời

5

Tài liệu Apple có điều này để nói về thuộc tính timeInterval trên NSTimer.

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

Nếu người nhận là một bộ đếm thời gian không lặp lại, trả về 0 (ngay cả khi một khoảng thời gian đã được thiết lập).

Bạn sẽ cần sử dụng một số phương tiện khác để theo dõi khoảng thời gian của bộ hẹn giờ. Tôi đề nghị một iVar trên lớp học của bạn.

-(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

Cảm ơn! Tôi đoán tôi nên đọc tài liệu lần sau. :) – Ivan

Các vấn đề liên quan