runloop mode應(yīng)用

亡羊補(bǔ)牢,為時(shí)不晚

面試被問(wèn)到,一直沒(méi)有注意過(guò),在此補(bǔ)上。

問(wèn)題描述

控制器中存在定時(shí)器以及tableview,當(dāng)滑動(dòng)tableview時(shí),定時(shí)器停止計(jì)時(shí),tableview再次停止后,計(jì)時(shí)恢復(fù)。

代碼測(cè)試

使用label顯示計(jì)時(shí)情況


計(jì)時(shí)
方案一:將定時(shí)器添加到其他線程,并開啟runloop
dispatch_async(dispatch_get_global_queue(0, 0), ^{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timeNumChange) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
});

- (void)timeNumChange {

    self.count++;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.timeNum.text = [NSString     stringWithFormat:@"runloop:%ld",self.count];
    
    });
}
方案二:將timer添加到指定mode(UITrackingRunLoopMode、NSRunLoopCommonModes)
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timeNumChange) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];

- (void)timeNumChange {

self.count++;
self.timeNum.text = [NSString stringWithFormat:@"runloop:%ld",self.count];

}

最后轉(zhuǎn)載一篇更詳細(xì)的文章:深入理解RunLoop

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容