When should I add / remove observers from UIApplication usage notifications?

When should I add and remove observers from UIApplication notifications?

- (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]; } 

and

 - (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]; } 

This is bad? I'm only interested in notifications when a view is displayed on the screen. And will there be problems removing UIApplicationWillEnterForegroundNotification in the viewWillDisappear: method? I think of the order in which everything happens ...?

+4
source share
1 answer

Do this in - (id)init{} or another appropriate initializer and - (void)dealloc{} . Adding and removing observers in the WillAppear and viewWillDisappear views would unnecessarily do this several times when you submit and reject modals, for example.

For projects with ARC, you can still implement the dealloc method. Just don't call [super dealloc] same as you did with Manual Retain / Release projects. In fact, the compiler will not allow you.

+1
source

All Articles