[NSTimer scheduledTimerWithTimeInterval:1.0 target:self
selector:@selector(updataTimer) userInfo:nil repeats:YES];
/*此操作会自动将timer放在Runloop的NSDefaultRunLoopMode中
但是当tableView滑动的时候,timer将暂停计时操作。如果不想UI阻值timer的运行,需如下操作
*/
NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self
selector:@selector(updataTimer) userInfo:nil repeats:YES];
//加入到运行循环 -- RunLoop
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
/*在此方法中,timer不管UI界面有无交互操作都不会影响timer的执行。
Ps:但是如果在updataTimer方法中进行了延时操作,比如sleep(1),就会卡住UI。
*/
NSTimer * timer2 = [NSTimer timerWithTimeInterval:1.0 target:self
selector:@selector(updataTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer2 forMode:UITrackingRunLoopMode];
/*例如,当tableView滑动的时候,timer才会执行。在这种特殊的情况下进行一些特殊的处理。*/
_finish = NO;
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSTimer * timer = [NSTimer timerWithTimeInterval:1.0 target:self
selector:@selector(updataTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
//在此子线程中,执行代码后,runloop线程被回收了,所以线程销毁了,所以timer也消失,也就不会调用(更不会持续调用)updataTimer。
//因此要让runloop跑起来.这样timer就会持续执行。
// [[NSRunLoop currentRunLoop] run];
//Ps:这种runloop的开启方式不建议使用,因为一旦开启就无法关闭。
NSLog(@"run");
//run 永远不会执行。因为前面有代码[[NSRunLoop currentRunLoop] run]; 相当于死循环。
while (!_finish) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
//循环判断。runloop转0.1秒后进行判断。
});
- (void)updataTimer{
NSLog(@"%@",[NSThread currentThread]);
static int num = 0;
if (num > 3) {
_finish = YES;
}
}
我们可以通过GCD的timer更简单快捷的进行timer的使用
//GCD定时器。
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
NSLog(@"--------%@",[NSRunLoop currentRunLoop]);
});
dispatch_resume(timer);
GCD延时操作
__weak typeof(self)weakSelf = self;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
weakSelf.view.backgroundColor = [UIColor redColor];
});
//C语言的写法
dispatch_after_f(dispatch_time(DISPATCH_TIME_NOW, 3 *NSEC_PER_SEC), dispatch_get_main_queue(), NULL, fun1);
void fun1()
{
NSLog(@"after 3s");
}