我已经开始学习iOS开发几周了,但是这个错误让我很困惑....
我只是在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];
}
我真的不知道我的代码有什么问题。谢谢。
答案 0 :(得分:2)
使用以下代码:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserverForName:@"OBSERVER NAME" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *aNotification)
{
//Write your Notification handler Code
}];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"OBSERVER NAME" object:nil];
}
此代码工作正常...... !!!
答案 1 :(得分:0)
尝试以下代码
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"notificationame" object:nil];