Take the 2-minute tour ×

when i read the api doc of the UINavigationController,the property navigationItem,has a tip:

Avoid tying the creation of bar button items in your navigation item to the creation of your view controller’s view

i don't understand what does this mean,can anybody explain this in detail

share|improve this question
add comment

1 Answer

This was probably added to the documentation quite recently as I stumbled across this today for the first time. Moreover, in nearly every sample code that I've seen the initialization of the bar buttons happens in the viewDidLoad method - which is obviously not the best place to do this according to the quoted statement.

What Apple says us with this is that there can be situations where the content of the navigationItem is requested when the viewDidLoad method is not executed yet or not gets executed at all. This happens when you push more than one viewcontroller at once. E.g. by using the setViewControllers:animated: interface or by doing something like this:

ViewController1 *firstViewController = [[ViewController1 alloc] init];
ViewController2 *secondViewController = [[ViewController2 alloc] init];
[navigationController pushViewController:firstViewController animated:YES];
[navigationController pushViewController:secondViewController animated:YES];

In this case the viewDidLoad method of firstViewController will not be called until the user navigates back to it. If you have set the title property in firstViewController, you would expect to have the back button labelled with the title you set in firstViewController. However the back button will be called "Back", as the title property of firstViewController is nil when UINavigationController asks for it.

The conclusion is: Tying the creation of bar button items to the creation of the view works for most situations. Nevertheless keep in mind that you can have situations where you need the navigationitem information before or without creating the view. In this case consider initializing the navigationItem property in the viewcontrollers init method.

share|improve this answer
add comment

Your Answer


