Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is a better way to remove Notification observer

I usually use NSNotification like the sample below:

In viewDidLoad:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(foo:) name:kName1 object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bar:) name:kName2 object:nil];

In viewDidUnload and dealloc:

[[NSNotificationCenter defaultCenter] removeObserver:self];

But a friend told me that I should not use [[NSNotificationCenter defaultCenter] removeObserver:self]; because it will remove all the observers including the super class's . He suggested me to use the following code to remove observer one by one.

[[NSNotificationCenter defaultCenter] removeObserver:self name:kName1 object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:kName2 object:nil];

I've checked the ASIHttpRequest library's code ( https://github.com/pokeb/asi-http-request ). It follows my friends' suggestion.

I want to know if my friend is right or not? In my opinion, since the current instance will be unload or dealloc, the super class's notification is also useless. And is there any system UIViewController subclass use notification?

like image 766
tangqiaoboy Avatar asked Apr 06 '12 06:04

tangqiaoboy


People also ask

How do I delete an observer in Objective C?

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.

What is notification observer in Swift?

Save. Notification Center use for broadcasting singles or notifying the methods at the same time. It uses the Observer pattern to inform registered observers when a notification comes in, using a central dispatcher called NotificationCenter.


1 Answers

Your friend is 100% correct. Though, it does not matter if you remove all notification observations in dealloc.
You mentioned viewDidUnload, and there the case is completely different, because the unloaded object will stay alive, and you don't know when the notification observations of the superclass are added again. If they are added in viewDidLoad you won't have a problem. If they are added in an init method you just lost a bunch of important notification observations.

Removing observations with specific names is good practice and should be done from the beginning.

like image 198
Matthias Bauch Avatar answered Sep 19 '22 17:09

Matthias Bauch