iOS Development Journal

Tips and Tricks Learned the Hard Way

Don't Reference View Controller Views in Init

This is more of a note to my future self:

Don’t reference a view controller’s view in an init method.

Why not? Well, let me tell you what I did.

The Setup

Custom UITableViewController subclass. Has a few custom variables that store useful data. An array of things to display, some basic text, etc. These all get set in a custom init method: initWithTitle:Items:. All very simple. These variables then get used in viewDidLoad to setup the table view, etc.

The Problem

[self.tableview registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELLID"]

Running that in my init function results in viewDidLoad running before I had set up the other variables. Which meant viewDidLoad was running before any of its variables were initialized correctly. Needless to say, this resulted in some strange behavior.

The Solution

Stop referencing the view in the init method.