我应该在什么时候添加/删除UIApplication通知的观察者



我应该在什么时候添加和删除UIApplication通知的观察者?

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(saveState) name:UIApplicationWillResignActiveNotification object:nil];
    [nc addObserver:self selector:@selector(loadState) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    [nc removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [nc removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
}

这不好吗?我只对视图在屏幕上时的通知感兴趣。在viewWillDisappear:方法中删除UIApplicationWillEnterForegroundNotification会有什么问题吗?我在想事情发生的顺序。。。?

- (id)init{}或另一个匹配的初始值设定项中执行,而不是在- (void)dealloc{}中执行。例如,在viewWillAppear和viewWillDisappear中添加和删除观察者会在呈现和消除模态时不必要地多次执行。

对于带有ARC的项目,您仍然可以实现dealloc方法。只是不要像手动保留/释放项目那样调用[super dealloc]。事实上,编译器不会让你这么做。

最新更新