IOS开发 实现定时器的方式有哪几种?【附代码】

今天爱分享给大家带来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);
}

人已赞赏
IOS

IOS开发 define和const变量有什么区别?【附代码】

2020-10-20 17:21:53

IOS

Mac OmniGraffle 画图工具 网盘下载地址【最新】

2020-10-22 10:31:38

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
'); })();