我有三个 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
方法没有被调用。所以明显的问题是当我为 notification
removeObserver's
时。
我的问题是,如果到目前为止我所做的一切都是正确的,为什么当我删除 removeObserver
时它不起作用?如果不正确,我可以在哪里removeObserver's
?
最佳答案
你所做的一切都是对的。这就是通知的工作方式。 如果你的类 A、B 总是需要处理更新,你就不会移除观察者。 因为你在 viewDidLoad 中添加了你的“addObserver”。这意味着你只添加一次观察者。 正常的错误是你在“viewWillAppear”或“viewDidAppear”中添加“addObserver”,它会在类中添加多次观察者。然后,您必须在 viewDidDisappear 中删除 Observer。
关于ios - 我应该把 removeObserver 从 NSNotification 放在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30905896/