One xib File with Multiple "File's Owner"s

Matthew Frederick picture Matthew Frederick · May 1, 2011 · Viewed 12.9k times · Source

I've got three different UITableViews, each in it's own view, accessed via tabs. All three tables would ideally share the same custom UITableViewCell class and .xib file.

I started with one table, setting the class of the .xib to my custom class and the File's Owner of the .xib to the table's parent UIViewController, which works great. All of the custom view-related code is in the cell's class (background images based on a property set by the controller, custom cell height based on the number of lines a label requires based on a cell property set by the controller, etc.).

The result is nice: the cell is responsible for all of the visual layout and responding to user actions on the cell's controls, while the view controller is responsible for creating the cells and setting their data.

Now that I need to reuse the cell in other tables, though, the fact that the custom cell's .xib has a single File's Owner is a problem. Rather than duplicating the .xib file, is there a simple way to allow multiple controllers to own it?

Answer

Jonah picture Jonah · May 1, 2011

A nib's File's Owner is not strictly enforced. Instead it is only used to determine available outlets and actions, and to set bindings within Interface Builder. You can load a nib with any object as its File's Owner regardless of the class set in the nib file. When a nib is loaded it will send messages to the File's Owner to re-establish bindings. If the actual File's Owner object does not recognize those selectors you will have triggered an "unrecognized selector" exception. This means that if your nib binds some UITableViewCell to the 'cell' outlet of its File's Owner then any object with a 'cell' property could load that nib. You just need to be careful not to use this behavior to send an unrecognized selector or unexpected outlet class.

In your case, consider creating a single UIViewController subclass to act as the File's Owner of your nib. Have each of your three existing controllers extend that view controller subclass. That way they can all inherit the same set of properties expected by the nib file and all safely load that nib while still defining their own custom behavior.