Question

I'm using an addObserver like so:

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(notificationReceived:) name:nil object: nil];

Everything works well, but I thought it might be good form to remove the observer when I no longer needed it... I found that I needed to use this line:

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

Problem is, when I change my addObserver line to include the name so that the removeObserver will know which observer to remove, the notifications no longer get called. This line is run but ignored when the name is added:

[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(notificationReceived:) name:@"observerName" object: nil];

I can set the name back to nil and it works again. Anybody know what I'm doing wrong here?

Thanks!

Was it helpful?

Solution

I think you might be mistaken as the what the parameters mean.

The name: tells the system which notifications you want to be informed about.

self is the actual observer, so when you removeOberserver:self you will stop to receive any notifications.

You should read the documentation carefully again as to which have which meaning:

https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/doc/uid/20000219-SW1

For an example, see How to create a class to send and receive events through NSNotificationCenter in Objective-C?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top