一個(gè)NSTimer 和 NSRunloop 的有趣問題

近來看到一段 這樣的代碼

?while (retryCount < kMaxRetries) {?

? ? ? ? NSLog(@"current runloop is: %@",[NSRunLoop currentRunLoop]);

? ? ? ? NSLog(@"[count = %@]++++++ A...", @(retryCount));? ? ? ? ? ? ? ? ? ? ? ?CFRunLoopRunInMode(kCFRunLoopDefaultMode, kRetryDelay, false);

? ? ? ? NSLog(@"++++++ B...., %@", [NSThread currentThread]);

? ? }

居然可以 使用 runloop 來延時(shí)?

沒錯(cuò) 還是在 while 里面延時(shí)? 真是無比的神奇好用啊

實(shí)際上 這段代碼在 主線程里面是真的能用的

但是在 gcd 的后臺(tái)線程 就不會(huì)又延時(shí)?

整個(gè) while 會(huì)瞬間完成


這個(gè) 讓我想到了 NSTimer 和 runloop 的問題

- (void)testRunloop {? ? dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{

? ? ? ? if(!_timer) {

? ? ? ? ? ? _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(runLoopAction:) userInfo:nil repeats:true];

? ? ? ? ? ? _timer.tolerance= 10;

? ? ? ? }

// 如果不加這一句? 自然不會(huì)有問題

// 但是在主線程 下 那個(gè) 延時(shí)才有效

? ? ? ? [[NSRunLoop currentRunLoop] addTimer:_timer forMode: NSDefaultRunLoopMode];

? ? ? ? [self.timer fire];?

// 關(guān)鍵是這一句 加上 才能 在 GCD 里面? timer 的 repeat 才起到作用

? ? ? ? [[NSRunLoop currentRunLoop] run];

? ? });

}


- (void)runLoopAction:(id)sender {

? ? constNSUIntegerkMaxRetries = 3;

? ? constNSTimeIntervalkRetryDelay = 2;

? ? intretryCount = 0;

? ? while (retryCount < kMaxRetries) {??

? ? ? ? NSLog(@"current runloop is: %@",[NSRunLoop currentRunLoop]);

? ? ? ? NSLog(@"[count = %@]++++++ A...", @(retryCount));

? ? ? ? retryCount ++;

//? ? ? ? ? ? CFRunLoopRunInMode(kCFRunLoopDefaultMode, kRetryDelay, false);

// 換成了?NSRunLoop 一樣能 work 的

? ? ? ? [[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:kRetryDelay]];

? ? ? ? NSLog(@"++++++ B...., %@", [NSThread currentThread]);

? ? }

}


并沒有發(fā)現(xiàn)許多 runloop? 的實(shí)用之處

但是能延時(shí) 還真的蠻有用的

?著作權(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),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • iOS刨根問底-深入理解RunLoop 2017-05-08 10:35 by KenshinCui 概述 Run...
    mengjz閱讀 1,636評(píng)論 1 10
  • runtime 和 runloop 作為一個(gè)程序員進(jìn)階是必須的,也是非常重要的, 在面試過程中是經(jīng)常會(huì)被問到的, ...
    made_China閱讀 1,269評(píng)論 0 7
  • 這是AF2.x經(jīng)典的代碼: 首先我們要明確一個(gè)概念,線程一般都是一次執(zhí)行完任務(wù),就銷毀了。 而添加了runloop...
    有夢想的老伯伯閱讀 2,080評(píng)論 5 13
  • RunLoop的基本了解 **1 . RunLoop字面的意思 : **運(yùn)行循環(huán) / 跑圈 **2 . 基本作用 ...
    Mario_ZJ閱讀 591評(píng)論 1 3
  • runtime 和 runloop 作為一個(gè)程序員進(jìn)階是必須的,也是非常重要的, 在面試過程中是經(jīng)常會(huì)被問到的, ...
    SOI閱讀 22,009評(píng)論 3 63

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