Find and Remove Retained iOS Controllers in .NET
A controller that remains alive after navigation needs an ownership investigation. Rising memory alone does not identify a leak, because caches, native buffers and temporary allocations also contribute. Reproduce the same screen lifetime several times, find what still retains the unwanted object, and remove that reference at the boundary where the ownership should end.
.NET's collector and Objective-C reference counting coexist in an iOS application. A managed collection cycle and a cycle that crosses native objects are not equivalent. Long-lived events, notification callbacks and native delegate relationships can keep a controller reachable after its visible work is over. Microsoft lifetime guidance , iOS reference-cycle discussion
Establish a reproducible lifetime
Pick one navigation route and record the starting screen. Open the suspect screen, exercise its feature, return to the starting screen and repeat. Keep the data and actions consistent. Warm up image loading and other one-time initialization before comparing later repetitions.
On a Mac, use Xcode's memory graph to inspect retaining relationships and Instruments Allocations to compare generations around the repeated action. Record retained controller counts as well as process memory. A simulator's memory gauge does not establish safety on a physical device. Apple memory investigation
First check intentional owners. A controller still on a navigation stack is supposed to remain alive. So is one held in an application cache. Correct the expected lifetime before treating those references as defects.
Pair a notification with its visible lifetime
The following UIKit controller observes foreground entry only while it is visible. The observation helper returns a token that is disposed when observation should end. The token is also released during explicit controller disposal.
using System;
using Foundation;
using UIKit;
/// <summary>
/// Observes foreground entry only while this controller participates in the visible UI.
/// </summary>
public sealed class ForegroundController : UIViewController {
private NSObject? ForegroundObserver { get; set; }
public override void ViewDidLoad() {
base.ViewDidLoad();
View!.BackgroundColor = UIColor.SystemBackground;
Title = "Foreground example";
}
public override void ViewWillAppear(bool animated) {
base.ViewWillAppear(animated);
ForegroundObserver ??= UIApplication.Notifications.ObserveWillEnterForeground(HandleForeground);
}
public override void ViewDidDisappear(bool animated) {
StopObserving();
base.ViewDidDisappear(animated);
}
protected override void Dispose(bool disposing) {
if (disposing)
StopObserving();
base.Dispose(disposing);
}
private void StopObserving() {
var observer = ForegroundObserver;
ForegroundObserver = null;
observer?.Dispose();
}
private void HandleForeground(object? sender, NSNotificationEventArgs args) => Title = "Returned to foreground";
}
The null check prevents duplicate registration during repeated appearance callbacks. Clearing the stored token makes cleanup repeatable. This helper's documented token disposal ends observation. A raw NSNotificationCenter.AddObserver overload instead needs its own documented remove-token handling.
Foreground notification API
Install this controller in an existing UIKit navigation flow. While it is visible, background and foreground the application and check that its title changes. Navigate away and confirm that the inactive controller is no longer an observation target. Repeat the route to check for duplicate callbacks. Perform these UI operations on the main thread.
Fix the retaining owner
Visibility is the chosen boundary for this example, not a universal disposal rule. A background service may require observation while no screen is visible. Give that service its own subscription and lifetime instead of keeping a screen alive to receive callbacks.
For a long-lived managed publisher, retain the exact delegate needed for unsubscription and detach it when the subscriber's work ends. For native delegate or parent-child cycles, inspect which edge should be weak or explicitly cleared. Avoid a recursive helper that disposes every image, child view and data source it encounters. Shared resources may have other owners, and swallowing cleanup exceptions can conceal an invalid lifecycle.
Re-run the original route after the change. The useful result is that unwanted controller instances stop accumulating and the expected callbacks still occur. A forced garbage collection is at most a diagnostic aid, not a replacement for ending the retaining ownership.
This article develops the problems in Herman Schoenfeld's memory-leak question , follow-up answer and controller-disposal answer . Their recorded licenses are CC BY-SA 3.0, 4.0 and 3.0 respectively. The lifecycle example is new and does not reproduce the historical recursive disposal helper. Device profiling remains necessary to validate an application-specific fix.
Author: Herman Schoenfeld