我有一个简单的viewController,我想监听UIKeyboardWillHideNotification
。因此我有以下代码:
- (void) viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillBeHidden)
name:UIKeyboardWillHideNotification object:nil];
}
- (void) keyboardWillBeHidden
{
[self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}
我正在尝试决定何时删除 viewController 作为通知中心观察者。当 View Controller 在屏幕上时,我只需要知道 UIKeyboardWillHideNotification
,因此我正在考虑添加以下内容:
- (void) viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
这足够了吗?当viewController仍在屏幕上时,是否有可能调用viewDidUnload
或dealloc
?请注意,我使用的是非常基本的 UINavigationController
用于我的应用程序的流程。
最佳答案
在 viewWillAppear
中注册通知并在 viewWillDisappear
中取消注册对我来说似乎是一个干净且对称的解决方案。
请注意,viewWillAppear
可以在 dealloc
之前多次调用(例如,如果另一个 View Controller 被推送到您的 VC 上,或者您在选项卡栏 Controller 之间切换。)您在 viewWillAppear
中注册通知并仅在 dealloc
中取消注册,那么您将获得重复注册(比较 Warning for iOS/iPhone users about duplicate NSNotification observations ),并且针对单个通知多次调用已注册的选择器事件。
我实际上更喜欢基于 block 的观察者注册方法
addObserverForName:object:queue:usingBlock:
返回一个不透明对象,用于再次删除观察者。将此返回值存储到 View Controller 的实例变量中有助于跟踪观察者是否已注册,因此有助于避免重复注册。
关于iphone - NSNotificationCenter 关于 ViewWillAppear 和 ViewWillDisapper,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15721818/