I am wondering if it is a good practice to implement a deinit
on every view controller to check if it is correctly removed when it disappears and avoiding leaking memory?

- 30,560
- 17
- 97
- 143

- 1,113
- 1
- 9
- 20
-
Definitely not for just "checking something". Also, for controllers usually makes sense to use their own life cycle methods. – Sulthan Oct 14 '17 at 14:15
-
It is good practice for testing/development/debugging, but not for release. Once you have good "memory hygiene" then memory leaks should become rare/nonexistent. – Duncan C Oct 14 '17 at 15:37
3 Answers
By default, you don't have to implement the deinit
method in your classes:
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.
Usually, when working with View Controllers it seems that there is no need to do such an implementation. However, as mentioned in @rmaddy's comment, it is still an approach for tracing memory leak or reference cycle with the view controller.
If your purpose is to check if the controller has been removed from the hierarchy (view controller life cycle), you could implement 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, explanation for deinit not called).
Also:
these Q&As should be useful:

- 30,560
- 17
- 97
- 143
-
1tl;dr - yes, using `deinit` is one way to verify you don't have a memory leak or reference cycle with the view controller. – rmaddy Oct 14 '17 at 17:17
Swift automatically deallocates your instances when they are no longer needed, to free up resources. So to add deinit
on all your viewControllers
seems unnecessary. You should call deinit
whenever you need to do some action or cleanup before deallocating an object.

- 38,237
- 7
- 103
- 107
Well during the tests phase it maybe good idea, because you can check if everything is good (eg. if you have a lot of completion handler) but overall it is unnecessary.

- 377
- 4
- 11