7

我通过在 ViewDidLoad 中添加以下代码来检测键盘的显示/隐藏:

[[NSNotificationCenter defaultCenter] addObserver:self 
                                         selector:@selector(keyboardDidHide:) 
                                             name:UIKeyboardDidHideNotification 
                                           object:nil];

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

在某些时候,虽然我想删除这些观察者,但不调用

 [[NSNotificationCenter defaultCenter] removeObserver:self];

因为这会删除所有观察者,而我还有其他不想被删除的观察者。我怎样才能只删除这两个?

4

3 回答 3

31
[[NSNotificationCenter defaultCenter] removeObserver:self 
                                                name:UIKeyboardDidHideNotification 
                                              object:nil];

[[NSNotificationCenter defaultCenter] removeObserver:self 
                                                name:UIKeyboardWillShowNotification 
                                              object:nil];
于 2013-02-02T13:25:31.533 回答
1

使用官方文档中描述的removeObserver:name:object:方法,删除特定通知名称的观察者。NSNotificationCentre

于 2013-02-02T13:31:10.337 回答
1

采用[[NsNotificationCenter defaultCenter] removeObserver:self name: UIKeyboardWillShowNotification object:nil]

于 2013-02-02T13:31:20.273 回答