結(jié)合NSRunLoop,NSThread, GCD 認(rèn)識(shí)定時(shí)器(NSTimer)與 UIScrollView的沖突

1,NSRunLoopCommonModes和Timer

1> scheduledTimerWithTimeInterval創(chuàng)建
/**
 scheduledTimerWithTimeInterval
 */
- (void)timerMethod1
{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(changeCount) userInfo:nil repeats:YES];
}
  • 如下圖:當(dāng)拖動(dòng)scrollView的時(shí)候,定時(shí)器停止了,手松開(kāi),定時(shí)器恢復(fù)運(yùn)行
scheduledTimerWithTimeInterval.gif

如果希望拖動(dòng)scrollView不影響定時(shí)器運(yùn)轉(zhuǎn),怎么整呢?接著往下探究

2> timerWithTimeInterval創(chuàng)建
有4中情況,都可以嘗試一下:

請(qǐng)注意下面前兩種情況區(qū)別,以及前兩種和后兩種的區(qū)別

/**
 timerWithTimeInterval addTimer:forMode:
 */
- (void)timerMethod2
{
    self.timer = [NSTimer timerWithTimeInterval:0.5 target:self selector:@selector(changeCount) userInfo:nil repeats:YES];
    /*
     1,設(shè)置Mode為NSDefaultRunLoopMode
     scrollview滾動(dòng),定時(shí)器停止;scrollview停止?jié)L動(dòng)不做操作,定時(shí)器繼續(xù)開(kāi)啟;
     */
//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
    /*
     2,設(shè)置Mode為UITrackingRunLoopMode
     scrollview滾動(dòng),定時(shí)器開(kāi)啟;scrollview停止?jié)L動(dòng)不做操作,定時(shí)器停止;
     */

//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];
    
    /*
     3,設(shè)置Mode為NSDefaultRunLoopMode 和 UITrackingRunLoopMode
     scrollview滾動(dòng) 或 停止,對(duì)定時(shí)器沒(méi)影響,定時(shí)器一直開(kāi)啟;
     */

//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
//    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];

    /*
     4,設(shè)置Mode為NSRunLoopCommonModes
     scrollview滾動(dòng) 或 停止,對(duì)定時(shí)器沒(méi)影響,定時(shí)器一直開(kāi)啟;
     */

    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)changeCount
{
    Count--;
    self.timerLbl.text = [NSString stringWithFormat:@"%zi",Count];

}

以上4種情況運(yùn)行結(jié)果:

  • NSDefaultRunLoopMode
NSDefaultRunLoopMode.gif
  • UITrackingRunLoopMode
UITrackingRunLoopMode.gif
  • NSDefaultRunLoopMode AND UITrackingRunLoopMode
NSDefaultRunLoopMode AND UITrackingRunLoopMode.gif
  • NSRunLoopCommonModes
NSRunLoopCommonModes.gif

重要的分析來(lái)了:

  • timerWithTimeInterval 不用scheduled方式初始化的,需要手動(dòng)addTimer:forMode: 將timer添加到一個(gè)runloop中。
    而scheduled的初始化方法將以默認(rèn)mode直接添加到當(dāng)前的runloop中.

  • 如果當(dāng)前線(xiàn)程就是主線(xiàn)程,也就是UI線(xiàn)程時(shí),某些UI事件,比如UIScrollView的拖動(dòng)操作,會(huì)將Run Loop切換成NSEventTrackingRunLoopMode模式,在這個(gè)過(guò)程中,默認(rèn)的NSDefaultRunLoopMode模式中注冊(cè)的事件是不會(huì)被執(zhí)行的。
    加到NSRunLoopCommonModes是可以執(zhí)行的

  • NSRunLoopCommonModes,這個(gè)模式等效于NSDefaultRunLoopMode和NSEventTrackingRunLoopMode的結(jié)合

2,多線(xiàn)程和Timer

NSRunLoopCommonModes和Timer中有一個(gè)問(wèn)題,這個(gè)Timer本質(zhì)上是在當(dāng)前線(xiàn)程的Run Loop中循環(huán)執(zhí)行的,因此Timer的回調(diào)方法不是在另一個(gè)線(xiàn)程的。那么怎樣在真正的多線(xiàn)程環(huán)境下運(yùn)行一個(gè)Timer呢?

很顯然多線(xiàn)程能很好的幫我們解決問(wèn)題。

1> NSThread和Timer
/**
 NSThread
 */
- (void)threadTimerMethod
{
    NSLog(@"主線(xiàn)程 %@", [NSThread currentThread]);
    
    //創(chuàng)建并執(zhí)行新的線(xiàn)程
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
    [thread start];
}

- (void)newThread
{
    @autoreleasepool
    {
        //在當(dāng)前Run Loop中添加timer,模式是默認(rèn)的NSDefaultRunLoopMode
        [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timer_callback) userInfo:nil repeats:YES];
        //開(kāi)始執(zhí)行新線(xiàn)程的Run Loop
        [[NSRunLoop currentRunLoop] run];
    }
}

//timer的回調(diào)方法
- (void)timer_callback
{
    NSLog(@"Timer %@", [NSThread currentThread]);
}
NSThreadAndNSTimer.gif
2> GCD和Timer

GCD中的Timer應(yīng)該是最靈活的,而且是多線(xiàn)程的。GCD中的Timer是靠Dispatch Source來(lái)實(shí)現(xiàn)的。

/**
     dispatch_source_create 創(chuàng)建timer
 
     dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, <#dispatchQueue#>);
     dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, <#intervalInSeconds#> * NSEC_PER_SEC, <#leewayInSeconds#> * NSEC_PER_SEC);
     dispatch_source_set_event_handler(timer, ^{
         <#code to be executed when timer fires#>
     });
     dispatch_resume(timer);

 */
- (void)gcdTimerMothod
{
    NSLog(@"主線(xiàn)程 %@", [NSThread currentThread]);
    //間隔還是2秒
    uint64_t interval = 2 * NSEC_PER_SEC;
    //創(chuàng)建一個(gè)專(zhuān)門(mén)執(zhí)行timer回調(diào)的GCD隊(duì)列
    dispatch_queue_t queue = dispatch_queue_create("my queue", 0);
    //創(chuàng)建Timer
    _timert = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //使用dispatch_source_set_timer函數(shù)設(shè)置timer參數(shù)
    dispatch_source_set_timer(_timert, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);
    //設(shè)置回調(diào)
    dispatch_source_set_event_handler(_timert, ^()
    {
        NSLog(@"Timer %@", [NSThread currentThread]);
    });
    //dispatch_source默認(rèn)是Suspended狀態(tài),通過(guò)dispatch_resume函數(shù)開(kāi)始它
    dispatch_resume(_timert);
}
GCDAndNSTimer.gif

demo源碼:TimerDemo

發(fā)現(xiàn)這樣寫(xiě)簡(jiǎn)書(shū)較為耗費(fèi)時(shí)間,不容易啊,歡迎提出問(wèn)題建議,更歡迎點(diǎn)贊。

參考延伸:

NSTimer講解的很到位的博客:
iOS: NSTimer使用小記

RunLoop刨析的很深的博文:
深入理解RunLoop
深入理解RunLoop

最后編輯于
?著作權(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)容

  • 一、什么是runloop 字面意思是“消息循環(huán)、運(yùn)行循環(huán)”。它不是線(xiàn)程,但它和線(xiàn)程息息相關(guān)。一般來(lái)講,一個(gè)線(xiàn)程一次...
    WeiHing閱讀 8,302評(píng)論 11 111
  • ios 常用的定時(shí)器有三種:NSTime,CADisplayLink和GCD。 NsTimer // 參數(shù):Int...
    殿小七閱讀 907評(píng)論 0 2
  • 首先看一段AF2.x經(jīng)典代碼: 首先我們要明確一個(gè)概念,線(xiàn)程一般都是一次執(zhí)行完任務(wù),就銷(xiāo)毀了。 而添加了runlo...
    涂耀輝閱讀 22,864評(píng)論 42 293
  • 一、什么是NSRunLoop NSRunLoop是消息機(jī)制的處理模式 NSRunLoop的作用在于有事情做的時(shí)候使...
    呦釋原點(diǎn)閱讀 718評(píng)論 0 2
  • ———送給那些回家在路上的游子們 那間低矮破舊的土屋 那棵搖曳彎脖的榆樹(shù) 那座沒(méi)有水流的小橋 那縷絲絲熟悉的味道 ...
    厚土高天閱讀 405評(píng)論 0 8

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