近來看到一段 這樣的代碼
?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í) 還真的蠻有用的