首页 > 编程语言 > 详细

NSTimer 的回调方法被主线程阻塞的解决方案

时间:2020-03-31 16:12:58      阅读:119      评论:0      收藏:0      [点我收藏+]

业务场景

公司项目新增开屏广告的业务,涉及到关闭倒秒的功能。使用的nstimer去处理这里逻辑

遇到的问题

NSTimer的回调方法会被后置的UI更新阻塞,出现卡顿,跳秒的现象

解决办法

子线程启动NSTImer,回调方法中回归主线程更新UI

 

关键代码

子线程启动NSTimer

    __weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        if (strongSelf) {
            strongSelf.countTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:strongSelf selector:@selector(countDown) userInfo:nil repeats:YES];
            NSRunLoop *runloop = [NSRunLoop currentRunLoop];
            [runloop addTimer:strongSelf.countTimer forMode:NSDefaultRunLoopMode];
            [runloop run];
        }
    });

 

主线程更新UI

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.jumpBTN setTitle:[NSString stringWithFormat:@"跳过 %lds",(long)self.count] forState:UIControlStateNormal];
    });

 

NSTimer 的回调方法被主线程阻塞的解决方案

原文:https://www.cnblogs.com/widgetbox/p/12605871.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!