Arrabidas92
Arrabidas92

Reputation: 1153

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

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?

Upvotes: 2

Views: 3440

Answers (3)

Ahmad F
Ahmad F

Reputation: 31645

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:

Upvotes: 5

user7482031
user7482031

Reputation:

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.

Upvotes: 1

Rashwan L
Rashwan L

Reputation: 38833

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.

Upvotes: 1

Related Questions