Last active
January 5, 2022 06:06
-
-
Save Visput/d40c5ceaefbc50c7377597ba0865c9df to your computer and use it in GitHub Desktop.
Swift implementation of weak timer which automatically deallocates when target is released.
This file contains 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
final class WeakTimer { | |
fileprivate weak var timer: Timer? | |
fileprivate weak var target: AnyObject? | |
fileprivate let action: (Timer) -> Void | |
fileprivate init(timeInterval: TimeInterval, | |
target: AnyObject, | |
repeats: Bool, | |
action: @escaping (Timer) -> Void) { | |
self.target = target | |
self.action = action | |
self.timer = Timer.scheduledTimer(timeInterval: timeInterval, | |
target: self, | |
selector: #selector(fire), | |
userInfo: nil, | |
repeats: repeats) | |
} | |
class func scheduledTimer(timeInterval: TimeInterval, | |
target: AnyObject, | |
repeats: Bool, | |
action: @escaping (Timer) -> Void) -> Timer { | |
return WeakTimer(timeInterval: timeInterval, | |
target: target, | |
repeats: repeats, | |
action: action).timer! | |
} | |
@objc fileprivate func fire(timer: Timer) { | |
if target != nil { | |
action(timer) | |
} else { | |
timer.invalidate() | |
} | |
} | |
} | |
// Usage: | |
let timer = WeakTimer.scheduledTimer(timeInterval: 2, | |
target: self, | |
repeats: true) { [weak self] timer in | |
// Place your action code here. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Starting from iOS 10+ you just could use: