带有NSNotification的removeObserver ...我做错了什么?

Der*_*rek 28 objective-c nsnotification ios

基本上,我有一个view1,在某些时候,调用view2(via presentModalViewController:animated:).当UIButton按下某个视图2时,view2在view1中调用一个通知方法,然后立即关闭.通知方法会弹出警报.

通知方法工作正常,并被适当调用.问题是,每次创建view1时(一次只能存在一个view1),我可能会NSNotification创建另一个view1因为如果我从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];
}
Run Code Online (Sandbox Code Playgroud)

View2.m

-(IBAction) buttonWasTapped {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"alert" 
                                                        object:nil];
    [self dismissModalViewControllerAnimated:YES];
}

-(void) dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*lds 61

-dealloc视图控制器关闭后,调用不会自动发生 - 在视图控制器的生命周期中仍然可能存在一些"生命".在该时间范围内,该视图控制器仍然订阅了该通知.

如果删除观察者-viewWillDisappear:或者-viewDidDisappear:,这会产生更为直接的影响:

- (void) viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self 
                                                    name:@"alert" 
                                                  object:nil];
}
Run Code Online (Sandbox Code Playgroud)


小智 6

如果要实现在去除观察员viewWillDisappear:还是viewDidDisappear:那么你不应该留在加观察者viewDidLoad.

而是将观察者添加到viewWillAppear:.您遇到的问题是因为当视图上显示任何视图时UIViewController,将发生对观察者的删除,并且由于您添加了viewDidLoad仅发生一次的观察者,因此它将丢失.

请记住,当您的主视图不在前面时,此方法适用于您不希望观察的对象.

另请注意,viewDidUnload已经折旧了.