Why does my view controller leak in UIKit?

Memory leaks in UIKit can occur for various reasons, often related to strong reference cycles or unintentional retain cycles between your view controllers and other objects. This can prevent your view controller from being deallocated, leading to increased memory usage and potential app crashes.

One common scenario is when you have closures or delegates that capture self strongly, which can hold a reference to the view controller, preventing it from being released. To prevent this, make sure to use weak references when capturing self in closures or delegates.

Another source of leaks is not invalidating observers, notifications, or timers. When a view controller is no longer needed but still subscribed to events, it can remain in memory longer than necessary.

To identify leaks, you can use tools like Xcode's Instruments, specifically the Allocations and Leaks instruments. This helps you detect the objects that are still in memory and trace their retain cycles.


memory leaks UIKit view controller strong reference cycles retain cycles Xcode Instruments