iOS NStimer 創(chuàng)建和多線程創(chuàng)建

前言:NStimer 創(chuàng)建有兩種方式,一種是需要手動(dòng)加入 RunLoop 中,另一種是默認(rèn)幫你開啟 RunLoop

一、手動(dòng)開啟 RunLoop

可以在當(dāng)前線程指定哪個(gè)RunLoopMode中開啟

NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

二、自動(dòng)開啟 RunLoop

默認(rèn)開啟的 RunLoop 是在主線程 NSDefaultRunLoopMode

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(time) userInfo:nil repeats:YES];

三、子線程使用 NStimer(手動(dòng)開啟 RunLoop)

  • 錯(cuò)誤方法:
dispatch_queue_t queue1 = dispatch_queue_create("112", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue1, ^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(handleGraceTimer:) userInfo:nil repeats:NO];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    });

注:上述代碼不會(huì)執(zhí)行?。。‘?dāng) NStimer在主線程里添加時(shí),主線程的 RunLoop 是默認(rèn)執(zhí)行的,但是子線程的RunLoop是需要手動(dòng)創(chuàng)建[NSRunLoop currentRunLoop] 和手動(dòng)開啟的[[NSRunLoop currentRunLoop] run];。上述代碼只是把 NStimer 添加到子線程的RunLoop中,但并未開啟當(dāng)前RunLoop。

  • 正確方法:
    dispatch_queue_t queue1 = dispatch_queue_create("112", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue1, ^{
        NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(time) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
        [[NSRunLoop currentRunLoop] run];
    });

四、子線程使用 NStimer(自動(dòng)開啟 RunLoop)

自動(dòng)開啟的也要注意子線程RunLoop的創(chuàng)建和開啟。

  • 正確方法:
dispatch_queue_t queue1 = dispatch_queue_create("112", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue1, ^{
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(time) userInfo:nil repeats:YES];
        [[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)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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