NSNotificationCenter调用两次 [英] NSNotificationCenter calling two times
问题描述
下面是我所拥有的.
- (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,但是它被调用了两次.
Now when I click side menu button in MainViewController, what I was expecting is call adjustShowMenu from NotificationListener once, however it is called twice.
下面是相同的NSLog.
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=
我期望的是
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中进行尝试,但结果相同.
Note: I also tried in viewDidAppear instead of viewDidLoad, but its giving same result.
当我在线搜索时,有很多答案要求删除Observer.我做了同样的事情,但是仍然有两次通知被调用.
When I searched online, many answers asked to removeObserver. I did same, but still twice notification is getting called.
推荐答案
根据在此处回答,下方,并且现在可以正常工作.
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];
}
这篇关于NSNotificationCenter调用两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!