See the Xamarin.iOS history on this.
The core issue was doing something like this:
class MyViewSubclass : UIView
{
public UIView? Parent { get; set; }
public void Add(MyViewSubclass subview)
{
subview.Parent = this;
AddSubview(subview);
}
}
//...
var parent = new MyViewSubclass();
var view = new MyViewSubclass();
parent.Add(view);
Appears to leak unless you do one of:
view.Parent = null;
view.RemoveFromSuperview();
This is a problem in .NET MAUI, because they would have to explicitly unset many values to solve issues.
To repro, click the button in the sample:
This creates a cycle:
class MyView : UIView
{
public UIDatePicker Picker { get; } = new UIDatePicker();
public MyView()
{
AddSubview(Picker);
Picker.ValueChanged += OnValueChanged;
}
// Use this instead and it doesn't leak!
//static void OnValueChanged(object? sender, EventArgs e) { }
void OnValueChanged(object? sender, EventArgs e) { }
}
MyView
-> UIDatePicker
-> EventHandler
-> MyView
You can solve this one by making the OnValueChanged
method static
.
Try the event-example
branch for further details.