How to remove an observer for NSNotification in a UIView?
Asked Answered
F

1

7

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?

Fulllength answered 23/12, 2010 at 2:46 Comment(2)
Just a heads-up, KVO refers to key-value observing, which is a different concept from NSNotificationCenter.Tyronetyrosinase
Oops, still a little new to all of this. :)Fulllength
T
12

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];
}
Tyronetyrosinase answered 23/12, 2010 at 2:49 Comment(5)
The problem is, dealloc is never called. I've put NSLog statements there and all. Maybe I need to remove the subview in my superview and then dealloc will be called.Fulllength
@sudo rm -rf If dealloc isn't being called, but initWithFrame: is being called more than once, it sounds like you have a memory leak. Make sure you're releasing the subviews as soon as you no longer need them (immediately after addSubview: is usually appropriate).Tyronetyrosinase
I have my subview created as an instance variable so I can access it in other methods. How should I deal with it then? Releasing it crashes my app.Fulllength
@sudo rm -rf addSubview: will retain the subview for as long as the parent view is still around, so you can safely release the view you added immediately afterward. If you still need a reference to it, you can keep it around until it's removed from the superview or until viewDidUnload is called (at which point you should just set it to nil). If its lifecycle doesn't coincide with your view controller's, then it would be appropriate to retain and release it on a more granular level.Tyronetyrosinase
Ah, I just fixed it. I forgot to remove the observer so it was trying to run a method on a non-existant view. Thank you for your help! I'll accept it as answer as soon as it's available.Fulllength

© 2022 - 2024 — McMap. All rights reserved.