4

我应该何时添加和删除 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];
}

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

4

1 回答 1

1

- (id)init{}或其他匹配的初始化程序中执行它,而- (void)dealloc{}不是。例如,当您呈现和关闭模式时,在 viewWillAppear 和 viewWillDisappear 中添加和删除观察者将不必要地多次执行此操作。

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

于 2011-06-24T18:09:35.270 回答