How to remove an observer for NSNotification in a UIView?

sudo rm -rf picture sudo rm -rf · Dec 23, 2010 · Viewed 8.6k times · Source

I've added an observer in a custom UIView I've created under initWithFrame:.

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

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

Answer

Justin Spahr-Summers picture Justin Spahr-Summers · Dec 23, 2010

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

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