NSNotificationCenter呼叫两次



以下是我所拥有的。

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=");
}

现在,当我单击MainViewController中的侧边菜单按钮时,我期望的是从NotificationListener调用adjustShowMenu一次,但是它被调用了两次。

下面是相同的NSLog。

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=

我期待的是

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

知道出了什么问题吗?

注意:我也尝试了viewDidAppear而不是viewDidLoad,但它给出了相同的结果。

当我在网上搜索时,许多答案要求删除观察者。我做了同样的事情,但仍然两次通知被调用。

根据这里的答案,我进行了如下更改,现在工作正常。

-(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];
}

最新更新