Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an observer for NSNotification in a UIView?

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?

like image 887
sudo rm -rf Avatar asked Dec 23 '10 02:12

sudo rm -rf


People also ask

How do I get rid of observer?

When removing an observer, remove it with the most specific detail possible. For example, if you used a name and object to register the observer, use removeObserver(_:name:object:) with the name and object.

How do I delete a specific observer in Swift?

Removing registered observer For Selector approach, use NotificationCenter. default. removeObserver(self, name: notificationName , object: nil) , to remove the observer. For Block based approach, save the token you obtained by registering for notification in a property.

How do I add an observer in Swift?

addObserver(self, — This is for the class where we are going to observer notification. selector: #selector(loginSuccess) — This is the method name, whenever notification will receive this method call. name: NSNotification.Name(“com.


1 Answers

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];
}
like image 158
Justin Spahr-Summers Avatar answered Sep 22 '22 05:09

Justin Spahr-Summers