A set of Roslyn C# code analyzers for finding memory leaks in iOS and MacCatalyst applications -- with potentially other ideas in the future.
For more information on the "circular reference" problem on Apple platforms, see:
Note that this "circular reference" situation would occur in Swift or Objective-C, so it is not a .NET-specific problem. It does not occur on Android or Windows platforms.
Don't define public
events in NSObject
subclasses:
public class MyView : UIView
{
// NOPE!
public event EventHandler MyEvent;
}
Don't declare members in NSObject
subclasses unless they are:
WeakReference
orWeakReference<T>
- Value types
class MyView : UIView
{
// NOPE!
public UIView? Parent { get; set; }
public void Add(MyView subview)
{
subview.Parent = this;
AddSubview(subview);
}
}
Don't subscribe to events inside NSObject
subclasses unless:
- It's your event via
this.MyEvent
or from a base type. - The method is
static
.
class MyView : UIView
{
public MyView()
{
var picker = new UIDatePicker();
AddSubview(picker);
picker.ValueChanged += OnValueChanged;
}
void OnValueChanged(object sender, EventArgs e) { }
// Use this instead and it doesn't leak!
//static void OnValueChanged(object sender, EventArgs e) { }
}