问题描述
基本上,我有一个view1,在某些时候,调用view2(通过 presentModalViewController:animated:
)。当按下view2中的某个 UIButton
时,view2会在view1中调用通知方法,然后立即关闭。通知方法会弹出一个警告。
Basically, I have a view1 which at some point, calls view2 (via presentModalViewController:animated:
). When a certain UIButton
in view2 is pressed, view2 is calls a notification method in view1 and immediately afterward is dismissed. The notification method pops up an alert.
通知方法正常工作并被适当调用。问题是,每次创建view1时(一次只能存在一个view1),我可能会创建另一个 NSNotification
,因为如果我从view0(菜单)开始to view1,然后来回几次,我从通知方法中获得了一系列相同的警报消息,就像我打开一个view1一样多次。
The notification method works fine and is called appropriately. The problem is, every time view1 is created (only one view1 should exist at a time), I presumably get another NSNotification
being created because if I go from view0 (the menu) to view1, then back and forth a few times, I get a series of the same alert message, one after another, from the notification method as many times as I opened a view1.
这是我的代码,请告诉我我做错了什么:
Here is my code, please tell me what I'm doing wrong:
View1.m
-(void) viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(showAlert:)
name:@"alert"
object:nil];
}
-(void) showAlert:(NSNotification*)notification {
// (I've also tried to swap the removeObserver method from dealloc
// to here, but it still fails to remove the observer.)
// < UIAlertView code to pop up a message here. >
}
-(void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
View2.m
-(IBAction) buttonWasTapped {
[[NSNotificationCenter defaultCenter] postNotificationName:@"alert"
object:nil];
[self dismissModalViewControllerAnimated:YES];
}
-(void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
推荐答案
致电 -dealloc 不会自动发生 - 在视图控制器的生命周期中仍然可能存在一些生命。在该时间范围内,该视图控制器仍然订阅了该通知。
Calling -dealloc
doesn't automatically happen after the view controller is dismissed — there can still be some "life" left in the view controller's lifetime. In that timeframe, that view controller is still subscribed for that notification.
如果您移除中的观察者-viewWillDisappear:
或 -viewDidDisappear:
,这将产生更直接的效果:
If you remove the observer in -viewWillDisappear:
or -viewDidDisappear:
, this will have a more immediate effect:
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:@"alert"
object:nil];
}
这篇关于带有NSNotification的removeObserver ......我做错了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!