简体   繁体   中英

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?

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.

In case of Swift, you doing it like this:

NSNotificationCenter.defaultCenter().removeObserver(self)

And in Swift 3:

NotificationCenter.default.removeObserver(self)

Unfortunately, there is no way to remove all observers of a specific notification in one place. While there are certainly cases where this would be nice, it would be a dangerous thing to do as generally, the object doing the observing should be responsible for adding and removing itself as an observer of a particular notification. This ensures no unpredictable behavior b/c observers can come and go so they configure and clean up after themselves.

If an object that generates notifications goes away, it won't matter to the observer as the observer doesn't know about that object anyway. It just means that object won't be generating any more notifications.

[EDIT: RESPONSE TO YOUR COMMENT RE CLASS B STOPPING CLASS A FROM OBSERVING]

I just saw your comment. There are different ways to accomplish this, particularly if class B knows about class A. As you reference classes it sounds like you want to affect all instances of a class vs a particular instance. If you have some condition you can check when handling the notification, that's how I would approach this. In the notification handler something like:

if ([self shouldRespondToNotificationNamed:notification.name]) {
   [self performNotificationAction];
}

If you don't have a condition you can check, then create one either in the class in question as an iVar or in a place where you can access it globally for all class instances. I generally use a singleton to store global app state that doesn't persist. If it persists, then use whatever method you're using for other state.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM