我有3个viewControllers
,我正尝试从viewController
3到viewController
1和2发送通知。我认为最好的方法是使用NSNotification
。这是我到目前为止的内容:
在C类中-发布通知
[[NSNotificationCenter defaultCenter] postNotficationName:@"Updated "object:self];
B班
在A类和B类中-首先注册以获取通知
// viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleUpdate:) name:@"Updated" object:nil];
-(void)handleUpdate:(NSNotification *)notification {
NSLog(@"recieved");
}
到目前为止,该方法有效。但是当我在A类和B类中注销它时:
- (void)viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
该handleUpdate
方法不会被调用。所以明显的问题是我什么时候removeObserver's
去notification
。
我的问题是,如果到目前为止我所做的一切都是正确的,为什么在删除时不起作用removeObserver
?如果不正确,我在哪里removeObserver's
?
您所做的一切都是对的。这就是通知的工作方式。如果您的A,B类始终需要处理更新,则无需removeObserver。因为您在viewDidLoad中添加了“ addObserver”。这意味着您只添加一次addObserver。正常的错误是您在“ viewWillAppear”或“ viewDidAppear”中添加了“ addObserver”,它将在该类中添加多个观察者。然后,您必须在viewDidDisappear中删除Observer。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句