GCD定时器

iOS的定时器用法

大憨熊 提交于 2019-12-07 01:23:36
定时器在项目中还是经常用到的,很多情况下为了省事我们都是在主线程中直接用,但这样经常会造成阻塞,影响定时器的准确性,对时间精度要求比较高的地方还会给人很不好的体验,比如卡顿等等,所以,定时器的使用最好放在子线程中,下面就记录几种定时器的用法: 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

GCD定时器

帅比萌擦擦* 提交于 2019-12-06 10:40:52
GCD定时器 #####1.1.GCD定时器基本应用 -(void) baseGCD{ //创建一个GCD定时器 //<#dispatch_source_type_t type#> DISPATCH_SOURCE_TYPE_TIMER self.timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0 )); //设置定时器什么时候起动,间隔是多少 dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 2.0*NSEC_PER_SEC, 0); //设置定时器要做的事情 dispatch_source_set_event_handler(self.timer, ^{ NSLog(@"start --v%@",[NSThread currentThread]); }); //定时器默认是没有启动的,所以要托运启动 dispatch_resume(self.timer); } #####2.1.加强版GCD int count=0; -(void) GCD{ //GCD不受runLoop模式的影响 dispatch_queue_t queue=dispatch_get_global_queue(0,