简体   繁体   English

我应该在哪里删除通知观察员?

[英]Where should I remove a notification observer?

I set up a notification observer in my view controller's init method like so: 我在视图控制器的init方法中设置了一个通知观察器,如下所示:

[[NSNotificationCenter defaultCenter] 
                    addObserver:self
                    selector:@selector(saveState)
                    name:UIApplicationWillResignActiveNotification
                    object:nil];

Where is the best place to call removeObserver:name:object: for this notification. 调用removeObserver:name:object:的最佳位置在removeObserver:name:object:用于此通知。 I'm currently calling it in my dealloc method, but wanted to know if that might cause problems. 我现在用dealloc方法调用它,但想知道这是否会导致问题。

No, you got it right. 不,你做对了。 dealloc is the correct location to remove notification observers (unless you have some specific reason to need to remove the observer earlier). dealloc是删除通知观察者的正确位置(除非您有一些特定的理由需要先删除观察者)。

您始终可以在viewWillDisappear:删除观察者viewWillDisappear:或者当您完成使用它并且没有其它需要时,可以将其放在函数中。

如果-saveState只需要在活动时执行一次,那么您可以在-saveState中删除Observer。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM