使用GCD进行倒计时操作

来源:互联网 发布:seo软文免费发布渠道 编辑:程序博客网 时间:2024/05/19 09:12

地址:https://github.com/potato512/SYCategory

效果图:


代码示例:

// 倒计时+ (void)timerGCDWithTimeInterval:(NSTimeInterval)time maxTimerInterval:(NSInteger)maxTime afterTime:(NSTimeInterval)afterTime handle:(void (^)(NSInteger remainTime))handle{    if (0 >= maxTime)    {        return;    }        __block NSTimeInterval countdownTime = maxTime;    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), (time * NSEC_PER_SEC), 0);    dispatch_source_set_event_handler(timer, ^{                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(afterTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{                        if (0 >= countdownTime)            {                dispatch_async(dispatch_get_main_queue(), ^{                    if (handle)                    {                        handle(0);                    }                });                dispatch_source_cancel(timer);            }            else            {                dispatch_async(dispatch_get_main_queue(), ^{                    if (handle)                    {                        handle(countdownTime);                    }                });                countdownTime--;            }        });    });    dispatch_resume(timer);}
// 使用[NSTimer timerGCDWithTimeInterval:1.0 maxTimerInterval:300 afterTime:0 handle:^(NSInteger remainTime) {        self.label.text = [NSString stringWithFormat:@"%@", @(remainTime)];}];

注意事项:

使用了倒计时的视图控制器,退出当前视图控制器时,如果倒计时未完成时,则会继续执行倒计时计算,此时该视图控制器直到倒计时计算完成才被释放。



0 0