Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing all notification observer from a single place

I want to remove a notification observer and I am using the method:

[[NSNotificationCenter defaultCenter] removeObserver: name:@"myNotification" object:nil]; 

for this. Now there are many observers who are listening to this notification and I want to remove all of them in one shot from a centralised place. Can I pass 'nil' in first parameter and it will remove all observers who are listening to myNotification?

like image 665
Abhinav Avatar asked Apr 11 '11 17:04

Abhinav


People also ask

How do I get rid of observer notifications?

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 delete an observer in Objective C?

Removing the observer stops it from receiving notifications. If you used addObserverForName:object:queue:usingBlock: to create your observer, you should call this method or removeObserver:name:object: before the system deallocates any object that addObserverForName:object:queue:usingBlock: specifies.

Do we need to remove observers Swift?

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.

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.


2 Answers

You can remove an object from the notification center all together which means no notifications will get triggered. For example, when I have a view controller that has registered for notifications, I include this line in my dealloc.

[[NSNotificationCenter defaultCenter] removeObserver:self]; 

This is at the object level...so it will unregister for many notifications. It won't unregister for one notification in many objects.

Hope I understood your question correctly.

like image 116
Nathan Jones Avatar answered Sep 28 '22 05:09

Nathan Jones


In case of Swift, you doing it like this:

NSNotificationCenter.defaultCenter().removeObserver(self) 

And in Swift 3:

NotificationCenter.default.removeObserver(self) 
like image 27
Sruit A.Suk Avatar answered Sep 28 '22 07:09

Sruit A.Suk