处理倒计时问题的关键

在项目中我们常常需要设计到倒计时的问题,关于这个问题我刚开始也做错了好多,请看正确的思路。。。。。

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;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值