Stanley
Stanley

Reputation: 4486

Initializing a View Controller

When a view controller is first instantiated, it usually creates or loads objects it needs through its lifetime. It should not create views or objects associated with displaying content. It should focus on data objects and objects needed to implement other critical behaviors.

The above is from the iOS reference :

http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html#//apple_ref/doc/uid/TP40007457-CH10

The documentation goes on to describe a view load sequence with Storyboard.

My question are :

1

Since a view controller would be associated with a nib file, which contains view objects; And its "viewDidLoad" method seems to be designed for configuring view objects at load time. So how should the documentation's suggestion :

"should not create views or objects associated with displaying content"

be interpreted ?

2

Does question 1 related to whether we use Storyboard or not ?

Upvotes: 2

Views: 233

Answers (2)

He Shiming
He Shiming

Reputation: 5819

The statement you quoted has a lot to do with mobile device limitation and design efficiency. It does not relate to Storyboard in particular.

By "instantiating", the documentation meant the -(id)init; call. When this happens, the controller "prepares critical data, but not creates views". This means the controller evaluates a xib file, and constructs an internal hierarchical representation of the views upon init. This step involves only RAM and CPU.

View controller only creates views when it's pushed into the navigation controller, or view transition animation (that's when viewDidLoad kicks in). This is because views are expensive. It involves GPU and Video RAM. Video RAM is much more limited than RAM, it's not efficient to just create views (back buffer in VRAM) when it's not necessary to display.

If you look at your project, you should discover some view controllers being initialized but are not immediately required to show. Without such design, VRAM will drain quickly for no reason.

Upvotes: 1

Eimantas
Eimantas

Reputation: 49354

Not sure I get your question right, but here's my explanation:

  1. initialization and view creation are two separate steps. Let's say I have a view controller with table as IBOutlet which should display a list of recipes stored in core data. In my initialization method I'd fetch the data from CoreData and store it in an array or fetched results controller. I don't need table for that, hence I do nothing with self.view property (which calls the viewDidLoad if there is no view yet). In viewDidLoad I call [tableView reloadData] to redraw the cells so that they display the data from my controller created in controller's initializer.

  2. I don't think it's related, but storyboard should be mere scaffold for your view controllers replacing separate nibs with single file.

Upvotes: 1

Related Questions