When adding observer to the UIView causes memory leak in xamarin iOS

125 Views Asked by At

I prepared a custom control to enter numeric values and in my control loading I added a observer to get the device orientation change like in the below code snippet.

Foundation.NSNotificationCenter.DefaultCenter.AddObserver(new NSString("UIDeviceOrientationDidChangeNotification"), this.DeviceRotated);

The above line causes a memory leak in my custom control. Does anyone know how to resolve the memory leak issue caused by adding a Observer.

1

There are 1 best solutions below

0
On BEST ANSWER

I resolved the issue by disposing the NSObject as like in the code snippet.

    private NSObject deviceRotatedObserver;
this.deviceRotatedObserver = Foundation.NSNotificationCenter.DefaultCenter.AddObserver(new NSString("UIDeviceOrientationDidChangeNotification"), this.DeviceRotated);

protected override void Dispose(bool disposing)
        {
            if (this.deviceRotatedObserver != null)
            {
                this.deviceRotatedObserver.Dispose();
                this.deviceRotatedObserver = null;
            }
        }