iOS - CADisplayLink

CADisplayLink 属性及方法如下:

/*
 创建方法,刷新会触发 target的sel 方法
 */
+ (CADisplayLink *)displayLinkWithTarget:(id)target selector:(SEL)sel;

/*
 将receiver添加到runloop 和mode。每一个CADisplayLink只能添加到一种runloop上,但是可以一次添加到多个mode上。
 此操作会产生 retain
*/
- (void)addToRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode;

/*
 将receiver从runloop mode中移除。
 此操作会产生release
 */
- (void)removeFromRunLoop:(NSRunLoop *)runloop forMode:(NSRunLoopMode)mode;

/*
 从所有runloop mode移除(会release receiver),release target 。
*/
- (void)invalidate;

/* 上一次selector被调用的时间 */
@property(readonly, nonatomic) CFTimeInterval timestamp;

/*
 屏幕刷新时间间隔,iOS 每秒刷新60次,所以是 1/60s, 约16.7ms
 */
@property(readonly, nonatomic) CFTimeInterval duration;

/* 下一次selector被调用的时间 */
@property(readonly, nonatomic) CFTimeInterval targetTimestamp CA_AVAILABLE_IOS_STARTING(10.0, 10.0, 3.0);

/*
 暂停。默认是false, 当设置为true时,selector不会被触发
 */
@property(getter=isPaused, nonatomic) BOOL paused;

/*
 每隔多少次刷新触发selector。默认是1,每次刷新都触发。如果设置为2,表示每隔一次触发一次。
 小于1,设置无效。
 */
@property(nonatomic) NSInteger frameInterval
CA_AVAILABLE_BUT_DEPRECATED_IOS (3.1, 10.0, 9.0, 10.0, 2.0, 3.0, "use preferredFramesPerSecond");

/*每秒触发多少次,默认是60。设置为1,表示每秒触发一次。
 */
@property(nonatomic) NSInteger preferredFramesPerSecond CA_AVAILABLE_IOS_STARTING(10.0, 10.0, 3.0);

实现一个定时器


#import "ViewController.h"

@interface ViewController ()
@property (nonatomic,strong) CADisplayLink *displayLink;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(displayLinkAction:)];
//    frameInterval 默认值是1,表示每次更新display frame 都会触发displayLinkAction:。设置为2,表示每改变两次会触发selector。
//    self.displayLink.frameInterval = 2;

    // frameInterval 设置为60,因为屏幕每秒刷新60次,这样相当于一秒触发一次selector。
    self.displayLink.frameInterval = 60;

    [self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)displayLinkAction:(CADisplayLink*)displayLink{
    NSLog(@"--- displayLinkAction");
}

- (void)stop{
    [self.displayLink setPaused:YES];
    [self.displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    self.displayLink = nil;
}

@end

应用:

  • 动画
  • 检测帧率

其他参考文章:点我点我

猜你喜欢

转载自blog.csdn.net/liyun123gx/article/details/79472514
ios