Conditionally invalidate displayLink

Don't invalidate the CADisplayLink on deinit unless the  lazy display
link instance was already initialized previously.

- Closes #53
- Closes #54
This commit is contained in:
Matthew Seiler 2016-03-31 11:12:49 -04:00 committed by Reda Lemeden
parent 367144ac1f
commit aa6e103e42
No known key found for this signature in database
GPG Key ID: 2A4B46ECF1B02C90
1 changed files with 7 additions and 3 deletions

View File

@ -19,8 +19,12 @@ public class AnimatableImageView: UIImageView {
/// An `Animator` instance that holds the frames of a specific image in memory. /// An `Animator` instance that holds the frames of a specific image in memory.
var animator: Animator? var animator: Animator?
/// A flag to avoid invalidating the displayLink on deinit if it was never created
private var displayLinkInitialized: Bool = false
/// A display link that keeps calling the `updateFrame` method on every screen refresh. /// A display link that keeps calling the `updateFrame` method on every screen refresh.
lazy var displayLink: CADisplayLink = { lazy var displayLink: CADisplayLink = {
self.displayLinkInitialized = true
let display = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate)) let display = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
display.paused = true display.paused = true
return display return display
@ -110,13 +114,13 @@ public class AnimatableImageView: UIImageView {
/// Invalidate the displayLink so it releases its target. /// Invalidate the displayLink so it releases its target.
deinit { deinit {
// invalidate will also remove the link from all run loops if displayLinkInitialized {
displayLink.invalidate() displayLink.invalidate()
}
} }
/// Attaches the display link. /// Attaches the display link.
func attachDisplayLink() { func attachDisplayLink() {
displayLink.addToRunLoop(.mainRunLoop(), forMode: NSRunLoopCommonModes) displayLink.addToRunLoop(.mainRunLoop(), forMode: NSRunLoopCommonModes)
} }
} }