一个NSTimer 和 NSRunloop 的有趣问题

近来看到一段 这样的代码

 while (retryCount < kMaxRetries) { 

        NSLog(@"current runloop is: %@",[NSRunLoop currentRunLoop]);

        NSLog(@"[count = %@]++++++ A...", @(retryCount));                       CFRunLoopRunInMode(kCFRunLoopDefaultMode, kRetryDelay, false);

        NSLog(@"++++++ B...., %@", [NSThread currentThread]);

    }

居然可以 使用 runloop 来延时 

没错 还是在 while 里面延时  真是无比的神奇好用啊

实际上 这段代码在 主线程里面是真的能用的

但是在 gcd 的后台线程 就不会又延时 

整个 while 会瞬间完成


这个 让我想到了 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;

        }

// 如果不加这一句  自然不会有问题

// 但是在主线程 下 那个 延时才有效

        [[NSRunLoop currentRunLoop] addTimer:_timer forMode: NSDefaultRunLoopMode];

        [self.timer fire]; 

// 关键是这一句 加上 才能 在 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]);

    }

}


并没有发现许多 runloop  的实用之处

但是能延时 还真的蛮有用的

你可能感兴趣的:(一个NSTimer 和 NSRunloop 的有趣问题)