在这里主要介绍三种计时器吧,毕竟用的情况不是很多
首先是NSTimer
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeUp) userInfo:nil repeats:YES]; //解决timer方法延迟调用的情况 [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
然后是CADisplayLink
CADisplayLink *cadisplayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(timeUp)]; cadisplayLink.frameInterval = 60; [cadisplayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [cadisplayLink invalidate];
最后是GCD的dispatch_source_t
//只执行一次 double delayInSeconds = 2.0; __weak ViewController *weakSelf = self; dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ [weakSelf timeUp]; }); //重复执行 __block int timeout = 30; dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue); dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0); //每秒执行 dispatch_source_set_event_handler(_timer, ^{ if(timeout <= 0) { //倒计时结束,关闭 dispatch_source_cancel(_timer); dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"时间到,结束调用"); }); }else{ int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds]; dispatch_async(dispatch_get_main_queue(), ^{ //设置界面的按钮显示 根据自己需求设置 NSLog(@"%@",strTime); }); timeout--; } }); dispatch_resume(_timer);
好啦,以上几种就是我们在iOS开发中常用的计时器了哦,小伙伴们可以自己试试哦,还是蛮好用的
时间: 2024-11-11 10:49:14