I have the following code that adds an observer in the loading of the view.
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserverForName:@"com.app.livedata.jsonupdated"
object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notif) {
NSLog(@"JSONUPDATED");
}];
}
And this fires fine. However when the view is unloaded and I confirm the dealloc is called the Notification is still firing.
There doesn't seem to be a method for deactivating this 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.
specifies. If your app targets iOS 9.0 and later or macOS 10.11 and later, and you used addObserver(_:selector:name:object:) , you do not need to unregister the observer. If you forget or are unable to remove the observer, the system cleans up the next time it would have posted to it.
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.
default — This is the notification variable you can create it globally inside your class if you having more notifications. addObserver(self, — This is for the class where we are going to observer notification.
Seems the solution is to track the object in the View and then you can reference it in the dealloc methods.
id observer = [[NSNotificationCenter defaultCenter] addObserverForName: /* ... */ ];
And then remove as following:
[[NSNotificationCenter defaultCenter] removeObserver:observer];
observer = nil;
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