IOS 定时器

2018-01-30  本文已影响8人  小暖风

一: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);

上一篇 下一篇

猜你喜欢

热点阅读