John Lane
John Lane

Reputation: 1132

UIViewController best practice - loading

I have a simple view controller with some UI outlets. I am using ARC I do additional setup in the viewDidLoad such as setting label properties, if statements to dynamically resize some components, etc. My question is is the viewDidLoadthe best place to place this code? I've posted an example of some of the code I have in the method. Thanks.

self.messageTitleLabel.numberOfLines = 1;
self.messageTitleLabel.adjustsFontSizeToFitWidth = YES;
self.messageTitleLabel.minimumFontSize = 15.0f;
[self someMethodToReframeLabelHeight];

Upvotes: 1

Views: 209

Answers (3)

Lorenzo B
Lorenzo B

Reputation: 33428

As commented out by David, yes it's perfect to perform additional setups here. But be aware that in viewDidLoad no geometry has been already set for its view. So, if you need to arrange the position of a subview within the controller's view use viewWillAppear or viewDidAppear.

Hope that helps.

Upvotes: 1

eric.mitchell
eric.mitchell

Reputation: 8855

Yes. As David H mentioned, viewDidLoad is a good place for memory reasons- if your application receives a memory warning, your views will be set up again the next time they are loaded. Another important reason to use viewDidLoad, though, is that if you try to put the above code in init or initWithWhatever:, you will encounter some strange problems. The reason is that in the init method, the view has not yet been created and awakened from its .nib, and accessing it from there will disrupt the entire view controller cycle. If you aren't using a .nib, you can also do some basic setup in -loadView. Just make sure you call super any time you override one of these methods.

Upvotes: 0

David Hoerl
David Hoerl

Reputation: 41672

Yes, great place. Recall that in iOS, the system may unload your view due to memory pressure, and so you may get this message again later. Thus, having the code there that adjusts the newly loaded view is perfect.

Upvotes: 1

Related Questions