OGeek|极客世界-中国程序员成长平台

标题: ios - 我应该把 NSNotification 中的 removeObserver 放在哪里 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 08:07
标题: ios - 我应该把 NSNotification 中的 removeObserver 放在哪里

我有三个 viewControllers,我正在尝试从 viewController 3 向 viewController 1 和 2 发送通知。我认为最好的方法是使用 NSNotification。到目前为止,这是我所拥有的:

在 C 类中 - 发布通知

[[NSNotificationCenter defaultCenter] postNotficationName"Updated "object:self];

B类

在 A 类和 B 类中 - 首先注册通知

// viewDidLoad
[[NSNotificationCenter defaultCenter] addObserver:self selectorselector(handleUpdate name"Updated" object:nil];

-(void)handleUpdateNSNotification *)notification {
    NSLog(@"recieved");
}

到目前为止,这有效。但是当我在 A 类和 B 类中注销它时:

- (void)viewWillDisappearBOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

handleUpdate 方法没有被调用。所以明显的问题是当我 removeObserver's 获取 notification 时。

我的问题是,如果到目前为止我所做的一切都是正确的,为什么当我删除 removeObserver 时它不起作用?如果不正确,我在哪里可以removeObserver's



Best Answer-推荐答案


你所做的一切都是正确的。这就是通知的工作方式。 如果您的 A、B 类总是需要处理更新,您将不会删除观察者。 因为您在 viewDidLoad 中添加了“addObserver”。这意味着你只 addObserver 一次。 正常的错误是你在“viewWillAppear”或“viewDidAppear”中添加了“addObserver”,它会在类中添加不止一次的观察者。然后,您必须在 viewDidDisappear 中删除Observer。

关于ios - 我应该把 NSNotification 中的 removeObserver 放在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30905896/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4