IOS 定时器

一:NSTimer

1.NSTimer有两类实例化方式,timerWithTimeInterval和scheduledTimerWithTimeInterval。使用timerWithTimeInterval实例化之后,要调用fire,开始运行。并且,要将timer添加到runloop中。[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]。如果没有滑动的view,scrollView,textView等,就用NSDefaultRunLoopMode,否则就用NSRunLoopCommonModes。scheduledTimerWithTimeInterval会自动给你添加runloop,model为NSDefaultRunLoopMode。

2.如果是在子线程启动定时器,要开启子线程的runloop才行,[[NSRunLoop currentRunLoop] run]。如果是在主线程启动定时器就不需要,因为主线程的runloop是默认开启的。

二:GCD定时器

定时器要声明为成员属性

@property (nonatomic,strong) dispatch_source_t time;

NSTimeInterval period = 1.0;

dispatch_queue_t queue = dispatch_get_global_queue(0, 0);

 self.time = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);

 //设置开始时间

dispatch_time_tstart =dispatch_time(DISPATCH_TIME_NOW,0);

dispatch_source_set_timer(self.time, DISPATCH_TIME_NOW, period * NSEC_PER_SEC, 0);

    dispatch_source_set_event_handler(self.time, ^{

//执行

    });

    dispatch_resume(self.time);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容