iOS中定时器不准的两种情况及解决方案

来源:互联网 发布:狗哑药配方淘宝网 编辑:程序博客网 时间:2024/04/29 22:09
1.NSDefaultRunLoopMode模式中 优先处理输入源事件,处理输入源事件时,不能处理定时源事件

2.当主线程阻塞时,定时器也会阻塞

解决方案:

    //这里的本质是 NSDefaultRunLoopMode不能使用这种事件循环的模式

//    [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];

    

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

        //1.手动开启定时器

        NSTimer *timer = [NSTimertimerWithTimeInterval:1target:selfselector:@selector(timerAction)userInfo:nilrepeats:YES];

        //2.手动加入到事件循环中

        [[NSRunLoopcurrentRunLoop] addTimer:timerforMode:NSRunLoopCommonModes];

        //3.手动开启定时器

        [timer fire];

        //NSRunLoop 事件循环处理的事件有:1.输入源事件(滑动事件、触摸事件)2.定时源事件

        //NSDefaultRunLoopMode 模式中 优先处理输入源事件,处理输入源事件时,不能处理定时源事件

        [[NSRunLoopcurrentRunLoop] run];

    });


1 0
原创粉丝点击