Skip to content

Instantly share code, notes, and snippets.

@Visput
Last active January 5, 2022 06:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Visput/d40c5ceaefbc50c7377597ba0865c9df to your computer and use it in GitHub Desktop.
Save Visput/d40c5ceaefbc50c7377597ba0865c9df to your computer and use it in GitHub Desktop.
Swift implementation of weak timer which automatically deallocates when target is released.
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.
}
@zjfjack
Copy link

zjfjack commented Sep 14, 2018

Thanks for your effort.
Until now, I realise that Timer is a strong reference!

@atereshkov
Copy link

Starting from iOS 10+ you just could use:

let timer = Timer.scheduledTimer(withTimeInterval: 2, 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