I have a view controller where I am trying to call Timer.scheduledTimer(withTimeInterval:repeats:block)
by passing a function as block parameter, instead of creating a block on the fly. I have this view controller:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Timer.scheduledTimer(withTimeInterval: 5,
repeats: true,
block: onTimer)
}
deinit {
print("deinit \(self)")
}
func onTimer(_ timer: Timer) {
print("Timer did fire")
}
}
The call is retaining the view controller, so the controller is never deallocated.
I know I can make it work as I want by replacing the call with:
Timer.scheduledTimer(withTimeInterval: 5,
repeats: true) { [weak self] timer in
self?.onTimer(timer)
}
But I'd like to know if there is a way to send the onTimer
method directly and avoid the retain cycle.
Thanks.