How to remove observer for NSNotification in UIView?

I added an observer to the custom UIView that I created in initWithFrame:

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateZipFromLocation:) name:@"zipFoundFromLocation" object:nil]; 

The problem is that this view is a subview. When the view is loaded again, it calls the initWithFrame message again, adding two observers, and so on. How can I remove the observer when the view disappears? Since this is a UIView , it says viewWillDisappear:(BOOL)animated not a valid method. Any ideas?

+7
source share
1 answer

You said that initWithFrame: is called more than once, so I assume that this means that the view is destroyed and recreated. You can remove the view as an observer in dealloc , which will be called when the view is no longer saved by someone:

 - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; [super dealloc]; } 
+12
source

All Articles