Deinit 在 vi​​ewControllers 上实现它是一个好习惯吗?

Deinit is it a good practice to implement it on viewControllers?

我想知道在每个视图控制器上实现一个 deinit 以检查它是否在消失时被正确删除并避免内存泄漏是否是一个好习惯?

Swift 在不再需要时自动释放您的实例,以释放资源。因此,在所有 viewControllers 上添加 deinit 似乎是不必要的。每当您需要在释放对象之前执行某些操作或清理时,您应该调用 deinit

好吧,在测试阶段,这可能是个好主意,因为您可以检查是否一切正常(例如,如果您有很多完成处理程序),但总的来说没有必要。

默认情况下,您不必在 类:

中实现 deinit 方法

Swift automatically deallocates your instances when they are no longer needed, to free up resources. Swift handles the memory management of instances through automatic reference counting (ARC), as described in Automatic Reference Counting. Typically you don’t need to perform manual cleanup when your instances are deallocated. However, when you are working with your own resources, you might need to perform some additional cleanup yourself. For example, if you create a custom class to open a file and write some data to it, you might need to close the file before the class instance is deallocated.

Swift Deinitialization Documentation - How Deinitialization Works Section.

通常,在使用 View Controller 时,似乎没有必要进行这样的实现。然而,正如@rmaddy的评论中提到的,它仍然是一种使用视图控制器跟踪内存泄漏或引用循环的方法。

如果您的目的是检查控制器是否已从层次结构中删除(查看控制器生命周期),您可以实施 viewWillDisappear(_:) or viewDidDisappear(_:) methods; Note that calling on of these methods does not guarantees that the deinit will be called, i.e it does not mean that disappearing the view controller always leads to deallocate it (related: Deinit never called, ).

还有:

这些问答应该有用:

  • When should I use deinit?

  • Understand deinitialization and inheritance in swift language