NSRunLoop應(yīng)用在NSTimer上

NSTimer創(chuàng)建分兩種情況:

1、通過(guò) scheduledTimerWithTimeInterval 創(chuàng)建的NSTimer, 默認(rèn)就會(huì)添加到RunLoop的DefaultMode中。


_timer = [NSTimer scheduledTimerWithTimeInterval:2.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%@",[NSThread currentThread]);
    }];
// 雖然默認(rèn)已經(jīng)添加到DefaultMode中, 但是我們也可以自己修改它的模式 
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];

2、通過(guò) timerWithTimeIntervalalloc 創(chuàng)建的NSTimer, 不會(huì)被添加到RunLoop的Mode中,我們要調(diào)用 [[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執(zhí)行分兩種情況:

主線程:

NSRunLoop默認(rèn)開(kāi)啟,不用調(diào)用 [[NSRunLoop currentRunLoop] run];

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

子線程:

NSRunLoop需要自主開(kāi)啟,要調(diào)用 [[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];
   });
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 基本概念 進(jìn)程 進(jìn)程是指在系統(tǒng)中正在運(yùn)行的一個(gè)應(yīng)用程序,而且每個(gè)進(jìn)程之間是獨(dú)立的,它們都運(yùn)行在其專(zhuān)用且受保護(hù)的內(nèi)存...
    小楓123閱讀 1,001評(píng)論 0 1
  • 一、什么是RunLoop 基本作用: 保持程序的持續(xù)運(yùn)行; 處理App中的各種事件(比如觸摸事件、定時(shí)器事件、Se...
    magic_pill閱讀 969評(píng)論 0 0
  • Run loop 剖析:Runloop 接收的輸入事件來(lái)自?xún)煞N不同的源:輸入源(intput source)和定時(shí)...
    Mitchell閱讀 12,629評(píng)論 17 111
  • RunLoop 文章目錄 RunLoop簡(jiǎn)介 1.1 什么是RunLoop? 1.2 RunLoop和線程 1.3...
    May_d8f1閱讀 341評(píng)論 0 1
  • 文章目錄RunLoop簡(jiǎn)介1.1 什么是RunLoop? 1.2 RunLoop和線程1.3 默認(rèn)情況下主線程的R...
    lusen_b閱讀 452評(píng)論 0 2

友情鏈接更多精彩內(nèi)容