iOS定时器
2019-05-07 本文已影响0人
马维启
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullableid)userInfo repeats:(BOOL)yesOrNo;
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullableid)userInfo repeats:(BOOL)yesOrNo;
1、必须保证有一个活跃的RunLoop
scheduled开头的方法会自动把timer加入当前RunLoop
2、NSTimer的创建与撤销必须在同一个线程操作,不能跨越线程操作。
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue());
dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
x++;
NSLog(@"%d",x);
if(x == 5){
dispatch_cancel(self.timer);
}
});
dispatch_resume(_timer);