Where to put the registerNib method in a table view controller

Apr 1, 2012 17:15 · 230 words · 2 minute read iOS ios5 tableview UITableView

Here’s a quick workaround for a gotcha if you’re using iOS5’s registerNib: method in conjunction with a table view controller class that’s external to the controller of the view that contains the table.

Scenario: You’ve got a table view in a Storyboard (or standard xib file) which is controlled by a UITableViewController class which is separate to the class controlling the Storyboard (or view). You want to use a custom cell layout contained in a separate xib file.

Problem: In order to use the custom cell laid out in the xib, you want to use the registerNib technique. This needs to be called early on in the lifecycle of the table view’s controller. So where should this be done?

Solution: You need to be careful about which method you place the registerNib call in.

If this is done in the table view controller’s init method, the controller’s tableView property won’t have been set. As an external table view controller, the viewDidLoad method won’t get called because the controller isn’t actually managing a view.

A workaround is to create a separate method in the table view controller - say something like -(void)registerCell - and call this after the table view controller has been instantiated.

Here’s an example which sits in the Storyboard controller’s viewDidLoad method:

self.tableController = [[MyTableController alloc] init]; self.tableView.delegate = self.tableController; self.tableView.datasource = self.tableController; self.tableController.tableView = self.tableView; [self.tableController registerCell];