基本上,我有一个 view1,它在某些时候调用 view2(通过presentModalViewController:animated:
)。当 view2 中的某个UIButton
被按下时,view2 会调用 view1 中的通知方法,然后立即关闭。通知方法会弹出一个警报。
通知方法工作正常并且被适当地调用。问题是,每次创建 view1(一次只应该存在一个 view1)时,我大概会NSNotification
创建另一个,因为如果我从 view0(菜单)转到 view1,然后来回几次,我会得到一个一系列相同的警报信息,一个接一个,来自通知方法的次数与我打开视图的次数一样多。
这是我的代码,请告诉我我做错了什么:
查看1.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];
}