Search code examples
iosobjective-cnsnotificationcenternsnotifications

NSNotificationCenter calling two times


Below is what I have.

MainViewController.m

- (IBAction)sideMenuAction:(id)sender {
    NSLog(@"login==sideMenuAction");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ShowMySideMenuNotification" object:self];
}

NotificationListener.m

-(void)viewDidLoad {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ShowMySideMenuNotification" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adjustShowMenu) name:@"ShowMySideMenuNotification" object:nil];
}

-(void) adjustShowMenu {
    NSLog(@"notification adjustShowMenu=");
}

Now when I click side menu button in MainViewController, what I was expecting is call adjustShowMenu from NotificationListener once, however it is called twice.

Below is the NSLog for the same.

2015-01-20 12:27:30.798 abc[699:169314] login==sideMenuAction
2015-01-20 12:27:30.798 abc[699:169314] notification adjustShowMenu=
2015-01-20 12:27:30.799 abc[699:169314] notification adjustShowMenu=

What I was expecting is

2015-01-20 12:27:30.798 abc[699:169314] login==sideMenuAction
2015-01-20 12:27:30.798 abc[699:169314] notification adjustShowMenu=

Any idea what is going wrong?

Note: I also tried in viewDidAppear instead of viewDidLoad, but its giving same result.

When I searched online, many answers asked to removeObserver. I did same, but still twice notification is getting called.


Solution

  • As per answer here, I make changes as below and its working fine now.

    -(void) viewWillAppear:(BOOL)animated {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adjustShowMenu) name:@"ShowMySideMenuNotification" object:nil];
    }
    
    -(void) viewWillDisappear:(BOOL)animated {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ShowMySideMenuNotification" object:nil];
    }