Resource Management in View Controllers

View controllers are an essential part of managing your app’s resources. View controllers allow you to break your app up into multiple parts and instantiate only the parts that are needed. But more than that, a view controller itself manages different resources and instantiates them at different times. For example, a view controller’s view hierarchy is instantiated only when the view is accessed; typically, this occurs only when the view is displayed on screen. If multiple view controllers are pushed onto a navigation stack at the same time, only the topmost view controller’s contents are visible, which means only its views are accessed. Similarly, if a view controller is not presented by a navigation controller, it does not need to instantiate its navigation item. By deferring most resource allocation until it is needed, view controllers use less resources.

When memory available to the app runs low, all view controllers are automatically notified by the system. This allows the view controller to purge caches and other objects that can be easily recreated later when memory is more plentiful. The exact behavior varies depending on which version of iOS your app is running on, and this has implications for your view controller design.

Carefully managing the resources associated with your view controllers is critical to making your app run efficiently. You should also prefer lazy allocation; objects that are expensive to create or maintain should be allocated later and only when needed. For this reason, your view controllers should separate objects needed throughout the lifetime of the view controller from objects that are only necessary some of the time. When your view controller receives a low-memory warning, it should be prepared to reduce its memory usage if it is not visible onscreen.

Initializing a View Controller

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

Initializing a View Controller Loaded from a Storyboard

When you create a view controller in a storyboard, the attributes you configure in Interface Builder are serialized into an archive. Later, when the view controller is instantiated, this archive is loaded into memory and processed. The result is a set of objects whose attributes match those you set in Interface Builder. The archive is loaded by calling the view controller’s initWithCoder: method. Then, the awakeFromNib method is called on any object that implements that method. You use this method to perform any configuration steps that require other objects to already be instantiated.

For more on archiving and archiving, see Archives and Serializations Programming Guide.

Initializing View Controllers Programmatically

If a view controller allocates its resources programmatically, create a custom initialization method that is specific to your view controller. This method should call the super class’s init method and then perform any class specific initialization.

In general, do not write complex initialization methods. Instead, implement a simple initialization method and then provide properties for clients of your view controller to configure its behaviors.

A View Controller Instantiates Its View Hierarchy When Its View is Accessed

Whenever some part of your app asks the view controller for its view object and that object is not currently in memory, the view controller loads the view hierarchy into memory and stores it in its view property for future reference. The steps that occur during the load cycle are:

  1. The view controller calls its loadView method. The default implementation of the loadView method does one of two things:

    • If the view controller is associated with a storyboard, it loads the views from the storyboard.

    • If the view controller is not associated with a storyboard, an empty UIView object is created and assigned to the view property.

  2. The view controller calls its viewDidLoad method, which enables your subclass to perform any additional load-time tasks.

Figure 4-1 shows a visual representation of the load cycle, including several of the methods that are called. Your app can override both the loadView and the viewDidLoad methods as needed to facilitate the behavior you want for your view controller. For example, if your app does not use storyboards but you want additional views to be added to the view hierarchy, you override the loadView method to instantiate these views programatically.

Figure 4-1  Loading a view into memory

Loading a View Controller’s View from a Storyboard

Most view controllers load their view from an associated storyboard. The advantage of using storyboards is that they allow you to lay out and configure your views graphically, making it easier and faster to adjust your layout. You can iterate quickly through different versions of your user interface to end up with a polished and refined design.

Creating the View in Interface Builder

Interface Builder is part of Xcode and provides an intuitive way to create and configure the views for your view controllers. Using Interface Builder, you assemble views and controls by manipulating them directly, dragging them into the workspace, positioning them, sizing them, and modifying their attributes using an inspector window. The results are then saved in a storyboard file, which stores the collection of objects you assembled along with information about all the customizations you made.

Configuring the View Display Attributes in Interface Builder

To help you layout the contents of your view properly, Interface Builder provides controls that let you specify whether the view has a navigation bar, a toolbar, or other objects that might affect the position of your custom content. If the controller is connected to container controllers in the storyboard, it can infer these settings from the container, making it easier to see exactly how it should appear at runtime.

Configuring Actions and Outlets for Your View Controller

Using Interface Builder, you create connections between the views in your interface and your view controller.

Listing 4-1 shows the declaration of a custom MyViewController class’s two custom outlets (designated by the IBOutlet keyword) and a single action method (designated by the IBAction return type). The declarations are made in a category inside the implementation file. The outlets store references to a button and a text field in the storyboard, while the action method responds to taps in the button.

Listing 4-1  Custom view controller class declaration

@interface MyViewController()
@property (nonatomic) IBOutlet id myButton;
@property (nonatomic) IBOutlet id myTextField;
- (IBAction)myAction:(id)sender;

Figure 4-2 shows the connections you would create among the objects in such a MyViewController class.

Figure 4-2  Connections in the storyboard

When the previously configured MyViewController class is created and presented, the view controller infrastructure automatically loads the views from the storyboard and reconfigures any outlets or actions. Thus, by the time the view is presented to the user, the outlets and actions of your view controller are set and ready to be used. This ability to bridge between your runtime code and your design-time resource files is one of the things that makes storyboards so powerful.

Creating a View Programmatically

If you prefer to create views programmatically, instead of using a storyboard, you do so by overriding your view controller’s loadView method. Your implementation of this method should do the following:

  1. Create a root view object.

    The root view contains all other views associated with your view controller. You typically define the frame for this view to match the size of the app window, which itself should fill the screen. However, the frame is adjusted based on how your view controller is displayed. See “Resizing the View Controller’s Views.”

    You can use a generic UIView object, a custom view you define, or any other view that can scale to fill the screen.

  2. Create additional subviews and add them to the root view.

    For each view, you should:

    1. Create and initialize the view.

    2. Add the view to a parent view using the addSubview: method.

  3. If you are using auto layout, assign sufficient constraints to each of the views you just created to control the position and size of your views. Otherwise, implement the viewWillLayoutSubviews and viewDidLayoutSubviews methods to adjust the frames of the subviews in the view hierarchy. See “Resizing the View Controller’s Views.”

  4. Assign the root view to the view property of your view controller.

Listing 4-2 shows an example implementation of the loadView method. This method creates a pair of custom views in a view hierarchy and assigns them to the view controller.

Listing 4-2  Creating views programmatically

- (void)loadView
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame];
    contentView.backgroundColor = [UIColor blackColor];
    self.view = contentView;
    levelView = [[LevelView alloc] initWithFrame:applicationFrame viewController:self];
    [self.view addSubview:levelView];

Managing Memory Efficiently

When it comes to view controllers and memory management, there are two issues to consider:

Although some aspects of memory allocation are strictly yours to decide, the UIViewController class provides some methods that usually have some connection to memory management tasks. Table 4-1 lists the places in your view controller object where you are likely to allocate or deallocate memory, along with information about what you should be doing in each place.

Table 4-1  Places to allocate and deallocate memory




Allocating critical data structures required by your view controller

Initialization methods

Your custom initialization method (whether it is named init or something else) is always responsible for putting your view controller object in a known good state. This includes allocating whatever data structures are needed to ensure proper operation.

Creating your view objects


Overriding the loadView method is required only if you intend to create your views programmatically. If you are using storyboards, the views are loaded automatically from the storyboard file.

Creating custom objects

Custom properties and methods

Although you are free to use other designs, consider using a pattern similar the loadView method. Create a property that holds the object and a matched method to initialize it. When the property is read and its value is nil, call the associated load method.

Allocating or loading data to be displayed in your view


Data objects are typically provided by configuring your view controller’s properties. Any additional data objects your view controller wants to create should be done by overriding the viewDidLoad method. By the time this method is called, your view objects are guaranteed to exist and to be in a known good state.

Responding to low-memory notifications


Use this method to deallocate all noncritical objects associated with your view controller. On iOS 6, you can also use this method to release references to view objects.

Releasing critical data structures required by your view controller


Override this method only to perform any last-minute cleanup of your view controller class. Objects stored in instance variables and properties are automatically released; you do not need to release them explicitly.

On iOS 6 and Later, a View Controller Unloads Its Own Views When Desired

The default behavior for a view controller is to load its view hierarchy when the view property is first accessed and thereafter keep it in memory until the view controller is disposed of. The memory used by a view to draw itself onscreen is potentially quite large. However, the system automatically releases these expensive resources when the view is not attached to a window. The remaining memory used by most views is small enough that it is not worth it for the system to automatically purge and recreate the view hierarchy.

You can explicitly release the view hierarchy if that additional memory is necessary for your app. Listing 4-3 overrides the didReceiveMemoryWarning method to accomplish this. First, is calls the superclass’s implementation to get any required default behavior. Then, it cleans up the view controller’s resources. Finally, it tests to see if the view controller’s view is not onscreen. If the view is associated with a window, then it cleans up any of the view controller’s strong references to the view and its subviews. If the views stored data that needs to be recreated, the implementation of this method should save that data before releasing any of the references to those views.

Listing 4-3  Releasing the views of a view controller not visible on screen

- (void)didReceiveMemoryWarning
    [super didReceiveMemoryWarning];
    // Add code to clean up any of your own resources that are no longer necessary.
    if ([self.view window] == nil)
        // Add code to preserve data stored in the views that might be
        // needed later.
        // Add code to clean up other strong references to the view in
        // the view hierarchy.
        self.view = nil;

The next time the view property is accessed, the view is reloaded exactly as it was the first time.

On iOS 5 and Earlier, the System May Unload Views When Memory Is Low

In earlier versions of iOS, the system automatically attempts to unload a view controller’s views when memory is low. The steps that occur during the unload cycle are as follows:

  1. The app receives a low-memory warning from the system.

  2. Each view controller calls its didReceiveMemoryWarning method. If you override this method, you should use it to release any memory or objects that your view controller object no longer needs. You must call super at some point in your implementation to ensure that the default implementation runs. On iOS 5 and earlier, the default implementation attempts to release the view. On iOS 6 and later, the default implementation exits.

  3. If the view cannot be safely released (for example, it is visible onscreen), the default implementation exits.

  4. The view controller calls its viewWillUnload method. A subclass typically overrides this method when it needs to save any view properties before the views are destroyed.

  5. It sets its view property to nil.

  6. The view controller calls its viewDidUnload method. A subclass typically overrides this method to release any strong references it has to those views.

Figure 4-3 shows a visual representation of the unload cycle for a view controller.

Figure 4-3  Unloading a view from memory