NSTimer导致误差的原因

来源:互联网 发布:商家怎么联系淘宝小二 编辑:程序博客网 时间:2024/06/10 03:54
//NSTimer导致误差的原因:        /*     1、NSTimer加在main runloop中,模式是NSDefaultRunLoopMode,main负责所有主线程事件,例如UI界面的操作,复杂的运算,这样在同一个runloop中timer就会产生阻塞。          2、模式的改变。主线程的 RunLoop 里有两个预置的 Mode:kCFRunLoopDefaultMode 和 UITrackingRunLoopMode。          当你创建一个 Timer 并加到 DefaultMode 时,Timer 会得到重复回调,但此时滑动一个ScrollView时,RunLoop 会将 mode 切换为 TrackingRunLoopMode,这时 Timer 就不会被回调,并且也不会影响到滑动操作。所以就会影响到NSTimer不准的情况。          PS:DefaultMode 是 App 平时所处的状态,rackingRunLoopMode 是追踪 ScrollView 滑动时的状态。          */            //解决的方法:    //1、在主线程中进行NSTimer操作,但是将NSTimer实例加到main runloop的特定mode(模式)中。避免被复杂运算操作或者UI界面刷新所干扰。    self.timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(showTime) userInfo:nil repeats:YES];        [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];    }- (void)timerMethod2 {        //2、在子线程中进行NSTimer的操作,再在主线程中修改UI界面显示操作结果;    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];    [thread start];}-(void)newThread{    @autoreleasepool {                [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showTime) userInfo:nil repeats:YES];                [[NSRunLoop currentRunLoop] run];    }}-(void)showTime{    //1.一开始的时候系统就为我们将主线程的main runloop隐式的启动了。    //2.在创建线程的时候,可以主动获取当前线程的runloop。每个子线程对应一个runloop}

0 0
原创粉丝点击