前言: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];
});