集思广益复制粘贴IOS

iOS倒计时毫秒-仿唯品会倒计时

2016-09-01  本文已影响1227人  船长_
demo.gif

直接上代码

- (void)countTime{
    AFWeakSelf;
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] ;
    double currentTime = [self.model.promote_end_date doubleValue] - interval;
    __block float timeout= currentTime; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),0.1*NSEC_PER_SEC, 0); // 每100毫秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束,关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                // 倒计时结束,关闭处理

            });
        }else{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSTimeInterval interval = [[NSDate date] timeIntervalSince1970] ;
                double currentTime = [self.model.promote_end_date doubleValue] - interval;

                int currentHour  = currentTime / 3600;
                int currentMinute = (currentTime - currentHour*3600) / 60;
                int currentSeconds = currentTime - currentHour*3600 -currentMinute*60;
                int currentMsec = currentTime*1000 - currentHour*3600*1000 - currentMinute*60*1000 - currentSeconds*1000;
                
                weakSelf.hourLabelA.text = [NSString stringWithFormat:@"%d",currentHour/10];
                weakSelf.hourLabelB.text = [NSString stringWithFormat:@"%d",(currentHour%10)];
                weakSelf.minuteLabelA.text = [NSString stringWithFormat:@"%d",currentMinute/10];
                weakSelf.minuteLabelB.text = [NSString stringWithFormat:@"%d",currentMinute%10];
                weakSelf.secondLabelA.text = [NSString stringWithFormat:@"%d",currentSeconds/10];
                weakSelf.secondLabelB.text = [NSString stringWithFormat:@"%d",currentSeconds%10];
                weakSelf.msecLabel.text = [NSString stringWithFormat:@"%d",currentMsec/100%1000];
                
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    self.myTimer = _timer;
}

GCD定时器非常耗性能,耗内存,pop这个控制器的时候发现没有释放,
在控制器即将消失

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

       // 取出对应的cell,取消cell上的定时器
        NSIndexPath *indexP = [NSIndexPath indexPathForRow:0 inSection:0];
        MFMainCityDetailGrabCell *cell = [self.detailTableView cellForRowAtIndexPath:indexP];
        if (cell.myTimer) {
            dispatch_source_cancel(cell.myTimer);
            cell.myTimer = nil;
        }
}

求助,各位大神,有没有什么方法释放掉这个控制器????

上一篇下一篇

猜你喜欢

热点阅读