In Xamarin, if you observe / subscribe to a particularly-named NSNotification
in an object that is IDisposable
(this includes any class descended from NSObject
!), you MUST explicitly unsubscribe from it in your Dispose
handler, or you will get a segfault (the system will attempt to call a method at a memory location that is no longer valid). The pattern looks like this:
class MyClass : NSObject
{
// instance variable
private NSObject notificationObservationHandle;
MyClass()
{
notificationObservationHandle = NSNotificationCenter.DefaultCenter.AddObserver(notificationName, NotificationHandler);
}
void NotificationHandler(NSNotification notification)
{
// ... etc ...
}
private bool disposed = false;
override protected void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
NSNotificationCenter.DefaultCenter.RemoveObserver(notificationObserverHandle);
}
disposed = true;
base.Dispose();
}
}
}