NSRunLoop应用在NSTimer上

NSTimer创建分两种情况:

1、通过 scheduledTimerWithTimeInterval 创建的NSTimer, 默认就会添加到RunLoop的DefaultMode中。


_timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%@",[NSThread currentThread]);
    }];
// 虽然默认已经添加到DefaultMode中, 但是我们也可以自己修改它的模式 
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

2、通过 timerWithTimeIntervalalloc 创建的NSTimer, 不会被添加到RunLoop的Mode中,我们要调用 [[NSRunLoop currentRunLoop] addTimer:方法。

_timer = [NSTimer timerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%@",[NSThread currentThread]);
    }];
_timer = [[NSTimer alloc]initWithFireDate:[NSDate dateWithTimeIntervalSinceNow:2.0] interval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"timer:%@",[NSThread currentThread]);
    }];
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];

NSTimer执行分两种情况:

主线程:

NSRunLoop默认开启,不用调用 [[NSRunLoop currentRunLoop] run];

NSLog(@"主线程:%@",[NSThread currentThread]);
_timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%@",[NSThread currentThread]);
    }];

子线程:

NSRunLoop需要自主开启,要调用 [[NSRunLoop currentRunLoop] run];


__weak typeof(self) weakSelf = self;
dispatch_queue_t queue = dispatch_queue_create("zixiancheng", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
      NSLog(@"子线程:%@",[NSThread currentThread]);
      weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
          NSLog(@"%@",[NSThread currentThread]);
      }];
      [[NSRunLoop currentRunLoop] run];
   });
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 基本概念 进程 进程是指在系统中正在运行的一个应用程序,而且每个进程之间是独立的,它们都运行在其专用且受保护的内存...
    小枫123阅读 4,436评论 0 1
  • 一、什么是RunLoop 基本作用: 保持程序的持续运行; 处理App中的各种事件(比如触摸事件、定时器事件、Se...
    magic_pill阅读 4,410评论 0 0
  • Run loop 剖析:Runloop 接收的输入事件来自两种不同的源:输入源(intput source)和定时...
    Mitchell阅读 14,270评论 17 111
  • RunLoop 文章目录 RunLoop简介 1.1 什么是RunLoop? 1.2 RunLoop和线程 1.3...
    May_d8f1阅读 2,325评论 0 1
  • 文章目录RunLoop简介1.1 什么是RunLoop? 1.2 RunLoop和线程1.3 默认情况下主线程的R...
    lusen_b阅读 3,012评论 0 2