View Controller and View Creation

On the whole, a view controller is created exactly like any other object. A view controller instance comes into existence because you instantiate a view controller class, either in code or by loading a nib (Chapter 5). But the instantiation of a view controller introduces some additional considerations:

  • How will the view controller persist?
  • How will the view controller’s view get into the interface?
  • Where will the view controller’s view come from?

We begin with the issue of persistence. Even if you’re using ARC, memory must be managed somehow (Chapter 12). A view controller instance, once brought into existence, can eventually go right back out of existence if it is not retained; indeed, under ARC this danger is greater, because ARC won’t permit an object to leak accidentally. The distinction between a view controller and its view can add to the confusion. It is possible, if things are mismanaged, for a view controller’s view to get into the interface while the view controller itself is allowed to go out of existence. This must not be permitted. If it does, at the very least the view will apparently misbehave, failing to perform its intended functionality, because that functionality is embodied by the view controller, which no longer exists. (I’ve made this mistake, so I speak from experience here.)

Fortunately, Cocoa follows a simple rule: if you hand a view controller to some other object whose job is to use that view controller somehow, the ...

Get Programming iOS 6, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.