美文网首页
NSRunLoop应用在NSTimer上

NSRunLoop应用在NSTimer上

作者: Etre | 来源:发表于2016-12-22 14:54 被阅读0次

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];
   });

相关文章

  • NSRunLoop应用在NSTimer上

    NSTimer创建分两种情况: 1、通过 scheduledTimerWithTimeInterval 创建的NS...

  • NSTimer

    深入NSTimer(iOS)iOS 中的 NSTimer关于NSRunLoop和NSTimer的深入理解

  • runloop关系篇

    NSRunloop关系篇 1.NSRunloop 与 NSTimer .https://blog.csdn.net...

  • NSRunLoopCommonModes

    1、NSTimer需要设置为NSRunLoopCommonModes模式[[NSRunLoop currentRu...

  • NSTimer中的NSRunloop

    NSTimer与NSRunloop平时的运用 一, 简单的了解NSRunloop 从字面上看:运行循环、跑圈 其实...

  • NSTimer,NSRunLoop,autoreleasepoo

    引言 NSTimer内存泄漏真的是因为vc与timer循环引用吗?不是! 小伙伴们都知道,循环引用会造成内存泄漏,...

  • NSRunLoop和NSTimer

    一、什么是NSRunLoop NSRunLoop是消息机制的处理模式 NSRunLoop的作用在于有事情做的时候使...

  • NSRunloop跟NSTimer

    NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval...

  • iOS常见知识点

    1.滑动UIScrollView时不影响定时器NSTimer [[NSRunLoop mainRunLoop] a...

  • 10.NSTimer的使用笔记

    1.前言 2.定时器NSTimer的一个被添加进NSRunLoop的使用细节: 在NSTimer schedule...

网友评论

      本文标题:NSRunLoop应用在NSTimer上

      本文链接:https://www.haomeiwen.com/subject/fmacvttx.html