gpt4 book ai didi

ios - 观察者永远不会从 NSNotificationCenter 中移除

转载 作者:可可西里 更新时间:2023-11-01 04:52:47 25 4
gpt4 key购买 nike

我正在添加一个 View Controller 作为 UIKeyboardWillShowNotification 通知的观察者。

我的 viewDidLoad 中有这段代码:

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];

在我的 dealloc 中:

[[NSNotificationCenter defaultCenter] removeObserver:self];

即使在关闭 View Controller 时调用了 dealloc,也不会删除观察者。因此,当我第二次打开它时,NSNotificationCenter 将尝试通知旧对象,该对象已被释放,应用程序崩溃。

我在 StackOverflow 上看到了几个关于这个特定问题的问题,但没有一个答案对我有用。

我尝试在 viewWillDisappearviewDidDisappear 中删除观察者,但同样的问题发生了。

我正在使用 ARC。

最佳答案

您是否在 viewWillDisappear 中尝试过这段代码?

- (void)viewWillDisappear:(BOOL)animated 
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

根据您的解释,我认为问题不在于移除观察者。尝试从另一个 View Controller 触发观察者。如果它没有被触发,你就会知道删除成功了,当你第二次添加观察者时就会出现问题。

关于ios - 观察者永远不会从 NSNotificationCenter 中移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18402198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com