CausticMango

software for fun & profit

Sidebar
Menu

The Right Way to Load a Custom UITableCellView

Although there are lots of places online to get iOS programming tips, the quality of the information at most places is really pretty low.

For example, I needed to load up a custom UITableCellView from a xib created with Interface Builder. If you poke around online, you'll see several examples that involve loading the xib manually and walking down the object graph until you find a specific class. Fragile, brutish, and totally unnecessary.

The correct way is crazy simple. The xib loader is already expecting to hookup the object graph to the "owner" object (represented by the File's Owner in Interface Builder. If you only use the custom cell in one controller, just expose an IBOutlet for it's class, set your controller as the File's Owner class type, and wire it up in IB.

Let's assume your custom cell class is called MyCustomTableCellView and your controller that needs it is called MyCustomTableViewController. In the controller's header, add a property like this:

@interface MyCustomTableViewController : UITableViewController {
MyCustomTableCellView *customCell;
}

@property (nonatomic, assign) IBOutlet MyCustomTableCellView *customCell;

@end

Notice I'm using "assign" instead of "retain" because I don't want the controller to take ownership of the cell, just hold on to is momentarily so that the tableview can take it.

Synthesize the property and then when you need a new instance of MyCustomTableCellView from the xib, use this code:

[[NSBundle mainBundle] loadNibNamed:@"MyCustomTableCellView" owner:self options:nil];
cell = customCell;


Viola, custom cell view loaded painlessly.