Iva*_*van 5 objective-c foundation ios
我正在尝试使用NSTimer实现指数退避的重试逻辑.我的代码看起来像这样:
-(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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是计时器NSTimer scheduledTimerWithTimeInterval似乎忽略了我提供的间隔并始终将其设置为0.0.关于我在这里做错了什么的建议?
Apple文档对此timeInterval属性进行了说明NSTimer.
如果接收器是非重复定时器,则返回0(即使设置了时间间隔).
您将需要使用其他一些方法来跟踪计时器间隔应该是什么.我推荐你上课的iVar.
-(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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2555 次 |
| 最近记录: |