21

I don't know exactly what's the right place to set things like the tintColor of the NavigationBar or the title of my ViewController. It works in the -init method and the -viewLoad method too. What is the "best-practice" or "right way" to do this? Has one of those any advantages?

James Webster
  • 31,873
  • 11
  • 70
  • 114
d4n13l
  • 263
  • 2
  • 6

4 Answers4

24

The init methods (yes there is more then one) are where the UIViewController is initialized. Thus this is the place where you do stuff for the UIViewController and not its views.

If you use a nib to load you view then the best place to set any properties is the viewDidLoad method. This method gets called after the nib is loaded. If you set up the view programatically use the loadView method then this is the place to set UIControl properties.

Since the system can unload views to save memory, it will leave the UIViewController alone. Any properties set in the init methode will not be applied again, since the UIViewController is already initialized.

BallpointBen
  • 9,406
  • 1
  • 32
  • 62
rckoenes
  • 69,092
  • 8
  • 134
  • 166
1

the init method is used to initialize the viewController while viewDidLoad method is used to load your nib(i.e. your view). so when you want to do something with your viewController then use init method and when you want to do something with your view then use viewDidLoad.

Rohan
  • 2,939
  • 5
  • 36
  • 65
0

In simple terms init is for preparing data. viewDidLoad is for filling data into view.

According to Apple's Documents

Initialization methods

Task: Allocate critical data structures required by your view controller.

Discussion: Your custom initialization method (whether it is named init or something else) is always responsible for putting your view controller object into a known good state. Use these methods to allocate whatever data structures are needed to ensure proper operation.

viewDidLoad

Task: Allocate or load data to be displayed in your view.

Discussion: Use the viewDidLoad method to load any data objects you intend to display. By the time this method is called, your view objects are guaranteed to exist and to be in a known good state.

Roger Lee
  • 200
  • 1
  • 7
0

The right place is to set it in viewDidLoad. To know more about those methods, apple has provided the documentation

Ilanchezhian
  • 17,426
  • 1
  • 53
  • 55