Simon
Simon

Reputation: 25983

Do I need to remove an observer from the NSNotificationCenter once, or as many times as it was added?

in my viewDidLoad, I add my controller as an observer for two notifications:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:NetworkStatusChangedNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkLocationStatus:) name:LocationStatusChangedNotification object:nil];

in my dealloc, should I remove it once, or twice? The removeObserver method doesn't seem to specify a particular notification.

[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] removeObserver:self]; // is this required?

Upvotes: 2

Views: 1007

Answers (3)

Praveen S
Praveen S

Reputation: 10393

Documentation is the best way to clear your doubts:

The following example illustrates how to unregister someObserver for all 
notifications for which it had previously registered:

[[NSNotificationCenter defaultCenter] removeObserver:someObserver];

Upvotes: 2

Michał Zygar
Michał Zygar

Reputation: 4092

From Reference:

RemoveObserver: Removes all the entries specifying a given observer from the receiver’s dispatch table.

http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html

so you need to call it only once

Upvotes: 1

Chaitanya Gupta
Chaitanya Gupta

Reputation: 4053

You need to remove it only once.

If you need it, you can also use -removeObserver:name:object: to stop observing just one of the notifications.

Upvotes: 5

Related Questions