NSTimer 的回调方法被主线程阻塞的解决方案
业务场景
公司项目新增开屏广告的业务,涉及到关闭倒秒的功能。使用的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]; });