今天爱分享给大家带来IOS开发 实现定时器的方式有哪几种?【附代码】,希望能够帮助到大家。
NSTimer
注意: 子线程中runloop默认不开启,如果是在子线程创建timer,需要将它加入到runloop里面
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f repeats:YES block:^(NSTimer * _Nonnull timer) { NSLog(@"hello world"); }];
CADisplayLink
- (void)viewDidLoad { [super viewDidLoad]; // 关键帧刷新 // 当下一次屏幕刷新时调用(屏幕每一秒刷新60) CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(update)]; // 想要让CADisplayLink工作, 必须得要添加到主运行循环当中. [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]; } -(void)update{ NSLog(@"CADisplayLink"); }
GCD
// 倒计时 // countTime 倒计时的总时间 // interval 每次block回调的间隔的时间 - (void) countDownTime:(NSInteger)countTime interval:(float)interval block:(void (^)(NSInteger count))block{ __block NSInteger count = 1; __block NSInteger time = countTime; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t source = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(source, DISPATCH_TIME_NOW, interval*NSEC_PER_SEC, 0); dispatch_source_set_event_handler(source, ^{ if (time<=0) { dispatch_source_cancel(source); dispatch_async(dispatch_get_main_queue(), ^{ block(count); }); }else{ dispatch_async(dispatch_get_main_queue(), ^{ block(count); }); time--; count++; } }); dispatch_resume(source); }