Skip to content

View controllers memory leaks

Gleb edited this page Jan 23, 2024 · 1 revision

The initial idea of this tracking was being taken from this article.

The code can be found here.

How it works

A view controller can potentially cause a memory leak if it remains in memory after it has disappeared and should have been deallocated.

To monitor potential memory leaks in view controllers, we initiate a timer in the viewDidDisappear: method. If the view controller is not deallocated after a certain delay (currently set to 2 seconds) following viewDidDisappear, it could indicate a potential memory leak.

We account for exceptions where viewDidDisappear does not necessarily imply deallocation. For instance, when the view is in the navigation stack and the navigation is forward rather than backward, etc.

Exceptions

However, there are scenarios where this detection logic may not be applicable. For example, if your view controller is part of a reusable table view cell, the cell won't be deallocated immediately upon disappearing. In such cases, you should make your view controller conform to LeakCheckDisabled protocol. Doing so ensures that the leak detection event is not triggered for it:

public class MapCarouselViewController: LeakCheckDisabled {
    ...
}

You can also disable it for a SwiftUI view, which is the root view in a leaking UIHostingController:

struct BeachDetailsScreen: View, LeakCheckDisabled {
    ...
}

Clone this wiki locally