NotifcationCenter导致强大的参考周期-Swift 5

问题描述 投票:1回答:2

使用NotifcationCenter时,似乎获得了强大的参考周期。

我正在使用NotificationCenter观察设备的旋转。 (虽然有些人认为这不是确定设备旋转的最佳方法,但由于没有使用自动布局并且没有使用情节提要,这似乎是我唯一的选择)。

即使从deinit {}ViewController中删除观察者,也永远不会在viewWillDisappear中调用它。

viewDidDisappear

关于为什么发生这种情况以及如何解决的任何想法?

也对如何确定旋转检测的任何新想法持开放态度(尽管未使用自动布局或情节提要)。>>

要到达import UIKit class TestVC: UIViewController { deinit { print("TestClass Deinit") //not being triggered ever } @objc private func rotationDetected(sender: Any) { print("we rotated") } override func viewDidDisappear(_ animated: Bool) { //NotificationCenter.default.removeObserver(UIDevice.orientationDidChangeNotification) } override func viewWillDisappear(_ animated: Bool) { NotificationCenter.default.removeObserver(UIDevice.orientationDidChangeNotification) //NotificationCenter.default.removeObserver(self) //also doesn't work } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: .main, using: rotationDetected) } override func viewDidLoad() { super.viewDidLoad() } } ,我在上一个TestVC()中使用了self.navigationController?.pushViewController(TestVC(), animated: true),而在返回时,我使用了ViewController

[不存在pop,该班级将正确Observer

使用NotifcationCenter时,似乎获得了强大的参考周期。我正在使用NotificationCenter观察设备的旋转。 (尽管有些人认为这不是最好的方法……

swift automatic-ref-counting swift5 notificationcenter strong-references
2个回答
1
投票

这应该在deinit中起作用:


-1
投票

[如果您的应用定位到iOS 9.0和更高版本或macOS 10.11和更高版本,不需要在其dealloc方法中注销观察者的注册。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.