On viewWillAppear: and NSNotificationCenter

viewWillAppear: method can be one of the trickiest methods to understand. According to Apple’s documentation:

This method is called before the receiver’s view is about to be added to a view hierarchy and before any animations are configured for showing the view.

The problem arises when your app consist of a single view controller and you implement this method in hopes to be notified (or check your setup) when the user relaunches your app. Unfortunately viewWillAppearAnimated: only fires in between view controllers. So if you have a root view controller and a detail view controller, it will be called when the user switches from one to another, not when he/she reopens (assuming background state) your application.

If you want to be notified when your application is loaded every time, you will need to use NSNotificationCenter. Here is how you would set up notifications in viewDidLoad:

After setting up your notification center, you will need to implement applicationDidBecomeActive: method.

Of course you will need to release your NotificationCenter in viewDidUnload:

applicationDidBecameActive: will be called every single time your application is opened. It’s not cheap memory wise, but so far it is the best solution.

On viewWillAppear: and NSNotificationCenter

Leave a Reply

Your email address will not be published. Required fields are marked *