gpt4 book ai didi

swift - 如何将函数作为参数传递以避免保留循环?

转载 作者:可可西里 更新时间:2023-11-01 01:28:14 25 4
gpt4 key购买 nike

我有一个 View Controller ,我试图通过传递函数作为 block 参数来调用 Timer.scheduledTimer(withTimeInterval:repeats:block),而不是动态创建 block 。我有这个 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")
}
}

调用保留了 View Controller ,因此 Controller 永远不会被释放。

我知道我可以通过将调用替换为:

    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()

希望这对您有所帮助。

关于swift - 如何将函数作为参数传递以避免保留循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40182464/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com