CADisplayLink的使用

CADisplayLink的使用注意
一:循环引用问题

#pragma mark - life cycle
- (void)dealloc
{
    /** 销毁CADisplayLink */
    if (_myLink) {
        [self.myLink invalidate];
    }
    NSLog(@"DMFunctionCADisplayLinkViewController 释放");
}

#pragma mark - private method
- (void)myTimerAction:(CADisplayLink *)sender
{
    if (self.totalTime > 0) {
        NSLog(@"____%@", [NSNumber numberWithInteger:self.totalTime]);
        self.timeShowLabel.text = [NSString stringWithFormat:@"%@s", [NSNumber numberWithInteger:self.totalTime]];
        self.totalTime--;
    } else {
        NSLog(@"____%@", [NSNumber numberWithInteger:self.totalTime]);
        self.timeShowLabel.text = [NSString stringWithFormat:@"%@s", [NSNumber numberWithInteger:self.totalTime]];
        self.totalTime = 100;
    }
}

- (CADisplayLink *)myLink
{
    if (_myLink == nil) {
        /**
         *  CADisplayLink的使用注意
         *  一:循环引用问题
         */
        _myLink = [CADisplayLink displayLinkWithTarget:[DMWeakProxy proxyWithTarget:self] selector:@selector(myTimerAction:)];
        if (@available(iOS 10.0, *)) {
            _myLink.preferredFramesPerSecond = 60;
        } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
            // 这部分使用到的废弃API
            _myLink.frameInterval = 1;
#pragma clang diagnostic pop
        }
        
        /** 将CADisplayLink加入runloop */
        [_myLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
        
        /** 将CADisplayLink从runloop中移除 */
//        [_myLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes]
        _myLink.paused = YES;
    }
    
    return _myLink;
}

创建CADisplayLink对象,要注意循环引用
_myLink = [CADisplayLink displayLinkWithTarget:[DMWeakProxy proxyWithTarget:self] selector:@selector(myTimerAction:)];
创建完成之后需要将CADisplayLink加入runloop
[_myLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
销毁CADisplayLink对象
if (_myLink) {
[self.myLink invalidate];
}


CADisplayLink的使用_第1张图片
1

可以看到DMFunctionCADisplayLinkViewController正常释放

你可能感兴趣的:(CADisplayLink的使用)