在项目中我们常常需要设计到倒计时的问题,关于这个问题我刚开始也做错了好多,请看正确的思路。。。。。
1.每次进到页面调用的方法
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self createClockTimer];
}
2.创建定时器
- (void)createClockTimer{
_clockTimer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(doClockTimerOperation) userInfo:nil repeats:YES];
}
- (void)doClockTimerOperation{
//每次执行定时器时都先计算出总时间,这也是最关键的地方
[self changeDateToTime:([self.chargingResponseModel.started_at integerValue]+[self.chargingResponseModel.quantity integerValue]*3600) currentTime: [NSDate curDateTimeInterval]];//这份方法必须写在此处,若是写到viewwillappear或者viewdidload中在由页面到后台,定时器会暂停,并销毁,再返回到当前页面时,定时器从离开时开始,此时就会出现计时错误
self.second--;
if (self.second<=0 && self.minute>0) {
self.second=59;
self.minute--;
}
if (self.minute<=0 && self.clock>0) {
self.minute=59;
self.clock--;
}
if (self.clock<=0 && self.minute<=0 && self.second<=0) {
self.second=0;//防止出现-1s的情况
self.minute = 0;
self.clock = 0;
[self deallocAllTimer];//销毁定时器
[self chargeStop];//结束充电
}
}
- (void)changeDateToTime:(NSInteger)entTime currentTime:(NSInteger)currentTime{
NSInteger timeInterval= entTime - currentTime;
self.clock=timeInterval/3600;
self.minute=timeInterval%3600/60;
self.second=timeInterval%3600%60;
}