CADisplayLink 实现60s倒计时


 CADisplayLink

依赖屏幕刷新频率触发事件,最精确。最适合做 UI 刷新。目前iPhone屏幕刷新频率固定60HZ,如果以后iPhone出现120HZ的屏幕目前的代码就会出问题,兼容性差。

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) CADisplayLink *countDownTimer;
@property (nonatomic, assign) NSInteger count;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _count = 60;
    
    _countDownTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(timerRunEvent)];
    //每秒调用选择器的次数
    _countDownTimer.preferredFramesPerSecond = 1;
    [_countDownTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)timerRunEvent {
    _count--;
    
    if (_count <= 0) {
        if (_countDownTimer) {
            [_countDownTimer invalidate];
            _countDownTimer = nil;
        }
        
    } else {
        NSLog(@"%ld",_count);
    }
}

- (void)dealloc {
    if (_countDownTimer) {
        [_countDownTimer invalidate];
        _countDownTimer = nil;
    }
}


@end

相关