倒計時

- (void)GCDCountDown {
    __block NSInteger _activityTime = [_linkModel.lastGiveTimes integerValue];
    dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
   _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, globalQueue);
    dispatch_source_set_timer(_timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
    dispatch_queue_t mainQueue = dispatch_get_main_queue();
    dispatch_source_set_event_handler(_timer, ^{
        if (_activityTime <=0) {
            
            dispatch_source_cancel(_timer);
            dispatch_async(mainQueue, ^{
                //結束
                self.hourLabel.text = @"0";
                self.minuteLabel.text = @"0";
                self.secondLabel.text = @"0";
                self.millisecondLabel.text = @"0";
            });
        }else{
            _activityTime = _activityTime-1;
            
            dispatch_async(mainQueue, ^{
                
                //倒計時顯示
                NSInteger minute;
                minute = _activityTime/60;
                NSInteger second;
                second = _activityTime%60;
                
                if (minute<10) {
                    self.hourLabel.text = @"0";
                    self.minuteLabel.text = [NSString stringWithFormat:@"%ld", minute];
                }else if (minute>9&&minute<61) {
                    self.hourLabel.text = [NSString stringWithFormat:@"%ld", minute/10];
                    self.minuteLabel.text = [NSString stringWithFormat:@"%ld", minute%10];
                }
                
                if (second<10) {
                    self.secondLabel.text = @"0";
                    self.millisecondLabel.text = [NSString stringWithFormat:@"%ld", second];
                }else if (second>9&&second<60) {
                    self.secondLabel.text = [NSString stringWithFormat:@"%ld", second/10];
                    self.millisecondLabel.text = [NSString stringWithFormat:@"%ld", second%10];
                }
                
            });
            
            
        }
    });
    
    dispatch_source_set_cancel_handler(_timer, ^{ //計時器取消處理器;調用 dispatch_source_cancel 時執行
        NSLog(@"Cancel Handler");
    });
    dispatch_resume(_timer);
}

- (void)dealloc{
    if (_timer) {
        dispatch_source_cancel(_timer);
    }
    
}
相關文章
相關標籤/搜索