如何将函数作为参数传递以避免保留循环?
How to pass a function as parameter avoiding retain cycles?
我有一个视图控制器,我试图通过将函数作为块参数传递来调用 Timer.scheduledTimer(withTimeInterval:repeats:block)
,而不是即时创建块。我有这个视图控制器:
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")
}
}
调用保留了视图控制器,因此永远不会释放控制器。
我知道我可以将调用替换为:
Timer.scheduledTimer(withTimeInterval: 5,
repeats: true) { [weak self] timer in
self?.onTimer(timer)
}
但是我想知道有没有办法直接发送onTimer
方法,避免retain cycle。
谢谢。
您应该调用 invalidate() 方法:
This method is the only way to remove a timer from an RunLoop object.
The RunLoop object removes its strong reference to the timer, either
just before the invalidate() method returns or at some later point.
If it was configured with target and user info objects, the receiver
removes its strong references to those objects as well.
在您的代码中的某处,您应该实现:
timer.invalidate()
希望对您有所帮助。
我有一个视图控制器,我试图通过将函数作为块参数传递来调用 Timer.scheduledTimer(withTimeInterval:repeats:block)
,而不是即时创建块。我有这个视图控制器:
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")
}
}
调用保留了视图控制器,因此永远不会释放控制器。
我知道我可以将调用替换为:
Timer.scheduledTimer(withTimeInterval: 5,
repeats: true) { [weak self] timer in
self?.onTimer(timer)
}
但是我想知道有没有办法直接发送onTimer
方法,避免retain cycle。
谢谢。
您应该调用 invalidate() 方法:
This method is the only way to remove a timer from an RunLoop object. The RunLoop object removes its strong reference to the timer, either just before the invalidate() method returns or at some later point.
If it was configured with target and user info objects, the receiver removes its strong references to those objects as well.
在您的代码中的某处,您应该实现:
timer.invalidate()
希望对您有所帮助。