Search code examples
xamarinmemory-leaksxamarin.iosnsnotificationcenteraddobserver

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


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.


Solution

  • 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;
                }
            }