我有一个NSTimer
,我分别用以下方法暂停和恢复:
-(void) pauseTimer:(NSTimer *)timer {
self.scene.paused = YES;
pauseStart = [NSDate date];
previousFireDate = [timer fireDate];
[timer setFireDate:[NSDate distantFuture]];
}
-(void) resumeTimer:(NSTimer *)timer {
self.scene.paused = NO;
NSDate *currentDate = [NSDate date];
NSTimeInterval pauseTime = [currentDate timeIntervalSinceDate:pauseStart];
NSDate *neededFireDate = [NSDate dateWithTimeInterval:pauseTime sinceDate:previousFireDate];
[timer setFireDate:neededFireDate];
NSLog(@"Fire Date: %@", timer.fireDate); //returning null
}
没有正确重置开火日期,因为当我检查timer.fireDate时,它会显示null
。我们想要的只是这些方法暂停计时器并在调用resume方法时从中断处继续计时器。非常感谢任何帮助。
答案 0 :(得分:0)
我的解决方案与您的解决方案有一个不同之处。我恢复时重新创建一个计时器。以下是我的工作方式,并且工作得很好:
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSTimeInterval elapsedTime;
@property (nonatomic, strong) NSDate *startDate;
- (void)startTimer
{
NSTimeInterval timeInterval = 20.0f;
// Create a timer. Adjust the elapsed time.
_timer = [NSTimer scheduledTimerWithTimeInterval:(timeInterval - _elapsedTime)
target:self
selector:@selector(timerFireMethod:)
userInfo:nil
repeats:YES];
// Save the start date.
_startDate = [NSDate date];
}
- (void)timerFireMethod:(NSTimer *)theTimer
{
// Clean.
[_timer invalidate];
_timer = nil;
_elapsedTime = 0.0;
[self startTimer];
// Additional handling.
}
- (void)pauseTimer
{
// Clean.
[_timer invalidate];
_timer = nil;
// Save the elapsed time.
_elapsedTime = [[NSDate date] timeIntervalSinceDate:_startDate];
}
希望它有所帮助。