我有一个视图view1,它在某个时候通过presentModalViewController:animated:
调用视图view2。当view2中的某个UIButton
被按下时,view2会调用view1中的一个通知方法并立即关闭。该通知方法会弹出一个警报。
通知方法可以正常工作并且可以适当地被调用。问题是,每次创建view1(同一时间只能存在一个view1),我可能会得到另一个NSNotification
的创建,因为如果我从view0(菜单)转到view1,然后来回几次,我会得到一系列相同的警报消息,从通知方法中打开与我打开view1的次数一样多的警报。
以下是我的代码,请告诉我我做错了什么:
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];
}
UIView
还是UIViewController
实例中调用的? - Alex Reynolds-viewWillDisappear:
是在UIViewController
子类中还是在UIView
子类中调用的?你必须只从UIViewController
中重写-viewWillDisappear:
。同时,确保添加你要移除观察的通知的name
和object
,这是你问题中的代码没有包括的部分(这可能解释了为什么它没有起作用)。 - Alex Reynolds-viewWillAppear:
中注册通知观察者,在-viewWillDisappear:
中取消注册。 - Alex Reynolds