NSTimer不准的问题及解决

Runloop Timer为什么不准?
1:Runloop Timer底层使用的timer精度不高;
2:与Runloop底层的调用机制有关系。

情况产生:
1、NSTimer被添加在mainRunLoop中,模式是NSDefaultRunLoopMode,mainRunLoop负责所有主线程事件,例如UI界面的操作,复杂的运算使当前RunLoop持续的时间超过了定时器的间隔时间,那么下一次定时就被延后,这样就会造成timer的阻塞。
2:模式的切换,当创建的timer被加入到NSDefaultRunLoopMode时,此时如果有滑动UIScrollView的操作,runLoop 的mode会切换为TrackingRunLoopMode,这是timer会停止回调。

解决:
1:在主线程中创建timer,timer添加到当前Runloop并设置RunloopType为NSRunLoopCommonModes。
2: 在子线程中创建timer,GCD操作:dispatch_source_create,创建定时器,dispatch_source_set_timer :设置定时器。dispatch_resume:启动。
3:CADisplayLink(频率能达到屏幕刷新率的定时器类):displayLinkWithTarget,addToRunLoop

#import 

@interface ViewController : UIViewController

/* 定时器 */
@property (nonatomic, strong) NSTimer *timer;

@property  (nonatomic , strong ) dispatch_source_t  atimer;

@end
#import "ViewController.h"

@interface ViewController ()

{
    UILabel *_label;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
    _label.center = self.view.center;
    _label.textColor = [UIColor blackColor];
    _label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:_label];
    
    //正常用法,作用于主线程的runloop,主线程要处理UI会影响精准度,Scollview滑动时mode切换为TrackingRunLoopMode,NSTimer会停止回调。
    [self normalUser];
    
    //1、在主线程中切换runloopMode
    [self mainloopchangemode];
    
    //2、异步线程创建NSTimer
    [self asyCreateTimer];
    
    //3、使用CADisplayLink
    [self userCADisplyLink];
}
int i = 0;
-(void)normalUser{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(addtime) userInfo:nil repeats:YES];
}
-(void)mainloopchangemode{
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
-(void)asyCreateTimer{
    self.atimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
    dispatch_source_set_timer(self.atimer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 1 * NSEC_PER_SEC );
    dispatch_source_set_event_handler(self.atimer, ^{
        self->_label.text = [NSString stringWithFormat:@"当前:%d",i];
        i++;
    });
    dispatch_resume(self.atimer);
}
-(void)userCADisplyLink{
    //较为精准,与屏幕刷新帧率同步,多用户视图渲染或绘图
    CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(addtime)];
    [link addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}
-(void)addtime{
    _label.text = [NSString stringWithFormat:@"当前:%d",i];
    i++;
}
@end

你可能感兴趣的:(NSTimer不准的问题及解决)