【发布时间】:2014-08-30 04:59:52
【问题描述】:
我已经开始学习 iOS 开发几个星期了,但是这个 bug 让我很困惑......
我只是在 ViewController 中发布了 4 个不同的观察者:(他们有不同的通知名称)
[[NSNotificationCenter defaultCenter]postNotificationName:@"notificationame" object:self userInfo:userinfo];
然后我想在另一个 ViewController 中添加和删除 4 个不同的观察者,如下所示:
-(void)viewwillappear{
self.localChangeObserver=[[NSNotificationCenter defaultCenter]addObserverForName:@"notificationame" object:nil queue:nil usingBlock:^(NSNotification *note) { }];
}
-(void)viewwilldisappear{
[[NSNotificationCenter defaultCenter]removeObserver:self.localChangeObserver];
}
但是这个“removeObserver”结果不起作用。每次我显示这个 ViewController 时,它都会增加一个观察者,(然后我隐藏这个 VC,什么都没有删除)。所以我最后得到了很多观察者。
而且,将它们放入 ViewDidLoad/dealloc 也不起作用。
但是,另外 2 个观察者工作正常。像这样:
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
我真的不知道我的代码有什么问题。非常感谢。
【问题讨论】:
-
如果那是您的真实代码,那么问题在于方法名称。
viewwilldisappear应该是viewWillDisappear。在每个方法中添加一个NSLog,并确保它在您期望的时候被调用。
标签: ios notifications observer-pattern