NSNotification being raised multiple times

A for Alpha picture A for Alpha · Feb 2, 2011 · Viewed 7k times · Source

i am developing a e-book reader and i had encountered the following issue. i am using an IBAction method to post a NSNotification which inturn invokes a action method once a button is tapped. It is working absolutely fine for the first time... The IBAction method has to be called evry time i tap on the button.After completing this action, i need to go to my home page and then come back and click the button again. This is where i am facing the problem. The Method is getting called more than once from the second time and the number only keeps increasing.. Please help me with this....

//IBAction Method
if (sender.tag == PenToolAction) {

    GLogInfo(@"Pen tool tapped");
    [self hideSelf];
    [[NSNotificationCenter defaultCenter] postNotificationName:PenToolActionInitialized object:nil];
}

Answer

Jilouc picture Jilouc · Feb 2, 2011

If you add the notification observer in a method called multiple times, you will receive the notification multiple times too.

Try to either put the [[NSNotificationCenter defaultCenter] addObserver:...] in the init method instead or call [[NSNotificationCenter defaultCenter] removeObserver:self] right before.