iOS的定时器用法
定时器在项目中还是经常用到的,很多情况下为了省事我们都是在主线程中直接用,但这样经常会造成阻塞,影响定时器的准确性,对时间精度要求比较高的地方还会给人很不好的体验,比如卡顿等等,所以,定时器的使用最好放在子线程中,下面就记录几种定时器的用法: 1、NSThread NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil]; [thread start]; - (void)newThread{ @autoreleasepool{ [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(requestMessages) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] run]; } } 2、GCD 首先定义timer: 这里有一点疑惑:timer若作为成员变量(定义放在@interface里面)定时器可以正常使用,但是在方法里面再去定义的定义的话定时器就完全不起作用了,还请知道的原因的小伙伴多多指教: NSTimeInterval period = 60.0; //设置时间间隔 dispatch