如何使用目标和CADisplayLink实例之间的弱引用在Swift中设置CADisplayLink

时间:2017-05-21 12:21:40

标签: swift weak-references cadisplaylink

在Objective-C中,我们可以使用代理模式初始化CADisplayLink以打破强引用:

WeakProxy *weakProxy = [WeakProxy weakProxyForObject:self];
self.displayLink = [CADisplayLink displayLinkWithTarget:weakProxy selector:@selector(displayDidRefresh:)];

然后,只需使dealloc中的displayLink无效:

- (void)dealloc
{
    [_displayLink invalidate];
}

但是,NSProxy似乎无法在Swift中继承:https://bugs.swift.org/browse/SR-1715

我试着这样写:

weak var weakSelf = self    
displayLink = CADisplayLink(target: weakSelf!, selector: #selector(displayDidRefresh(dpLink:)))

它不起作用。

我想知道是否有任何方法可以像在Objective-C中那样实现这一目标。

3 个答案:

答案 0 :(得分:4)

更好的方法可能是使显示链接无效 viewWill/DidDisappear,另见

获取有用信息。

如果这不是一个选项:使代理对象继承自NSObject 而不是NSProxy。例如,Objective-C解决方案 在这里给出

可以轻松转换为Swift 3:

class JAWeakProxy: NSObject {
    weak var target: NSObjectProtocol?

    init(target: NSObjectProtocol) {
        self.target = target
        super.init()
    }

    override func responds(to aSelector: Selector!) -> Bool {
        return (target?.responds(to: aSelector) ?? false) || super.responds(to: aSelector)
    }

    override func forwardingTarget(for aSelector: Selector!) -> Any? {
        return target
    }
}

然后可以用作

displayLink = CADisplayLink(target: JAWeakProxy(target: self),
                            selector: #selector(didRefresh(dpLink:)))

你的方法

weak var weakSelf = self    
displayLink = CADisplayLink(target: weakSelf!, selector: #selector(displayDidRefresh(dpLink:)))

不起作用,因为它在weakSelf时展开CADisplayLink 已初始化并传递强引用self作为目标。

答案 1 :(得分:1)

这个代理类应该可行。不要忘记在dealloc之前失效。

import UIKit

class CADisplayLinkProxy {

    var displaylink: CADisplayLink?
    var handle: (() -> Void)?

    init(handle: (() -> Void)?) {
        self.handle = handle
        displaylink = CADisplayLink(target: self, selector: #selector(updateHandle))
        displaylink?.add(to: RunLoop.current, forMode: .commonModes)
    }

    @objc func updateHandle() {
        handle?()
    }

    func invalidate() {
        displaylink?.remove(from: RunLoop.current, forMode: .commonModes)
        displaylink?.invalidate()
        displaylink = nil
    }
}

用法:

var displaylinkProxy = CADisplayLinkProxy(handle: { [weak self] in
                    self?.updateTime()
                })

答案 2 :(得分:1)

另一种解决方案,此解决方案从其外部API隐藏代理/ objc运行时。 DisplayLink一直存在,直到被变量引用为止。 一旦变量超出范围或设置为nil,CADisplayLink就会失效,因此也可以取消初始化目标。

import Foundation
import UIKit

/// DisplayLink provides a block based interface for CADisplayLink.
/// The CADisplayLink is invalidated upon DisplayLink deinit.
///
/// Usage:
/// ```
/// let displayLink = DisplayLink { caDisplayLink in print("Next frame scheduled \(caDisplayLink.targetTimestamp)") }
/// ```
///
/// Note: Keep a reference to the DisplayLink.
final class DisplayLink {
    let displayLink: CADisplayLink

    init(runloop: RunLoop? = .main, prepareNextFrame: @escaping (CADisplayLink) -> ()) {
        displayLink = CADisplayLink(
            target: DisplayLinkTarget(prepareNextFrame),
            selector: #selector(DisplayLinkTarget.prepareNextFrame))

        if let runloop = runloop {
            displayLink.add(to: runloop, forMode: .default)
        }
    }

    deinit {
        displayLink.invalidate()
    }
}

private class DisplayLinkTarget {
    let callback: (CADisplayLink) -> ()

    init(_ callback: @escaping (CADisplayLink) -> ()) {
        self.callback = callback
    }

    @objc func prepareNextFrame(displaylink: CADisplayLink) {
        callback(displaylink)
    }
}