Last active
August 21, 2019 08:34
-
-
Save aleclarson/e3ac0afce979eea429eb to your computer and use it in GitHub Desktop.
A block-based CADisplayLink for Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import QuartzCore | |
/// A block-based CADisplayLink wrapper. | |
/// You are expected to retain this until you no longer need it. | |
/// To prevent a retain cycle, you must use [unowned self] in the callback you pass. | |
public class DisplayLink { | |
public init (_ callback: Void -> Void) { | |
_callback = callback | |
_link = CADisplayLink(target: _DisplayTarget(self), selector: "_callback") | |
_link.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSRunLoopCommonModes) | |
} | |
private let _callback: Void -> Void | |
private let _link: CADisplayLink! | |
deinit { | |
_link.invalidate() | |
} | |
} | |
/// Retained by CADisplayLink. | |
private class _DisplayTarget { | |
init (_ link: DisplayLink) { | |
_link = link | |
} | |
weak var _link: DisplayLink! | |
@objc func _callback () { | |
_link?._callback() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Swift 5