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?
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.
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.
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.
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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With