Archive for September 16th, 2009


Creative nib tricks

Here’s an interesting read on creative exploitation of nib file binding behavior. Specifically, to load UITableViewCell instances:

This is what confused me at first:

   if (cell == nil) {

   [[NSBundle mainBundle] loadNibNamed:@”TVCell” owner:self options:nil];

   cell = tvCell;

   self.tvCell = nil;


The method loadNibNamed:owner:options returns an NSArray with the contents of the nib, but this code completely ignores that array. It doesn’t even capture it. Then, it goes on and blithely assigns some instance variable to another instance variable, and then sets the first instance variable to nil.

Yes, that does indeed look unintuitive, does it not?

Then it dawned on me. The bundle loader automatically connects outlets made to File’s Owner when it loads a nib file if the outlet is nil. Notice that when the nib is loaded, the code specifies self as the bundle’s owner. So, since this controller class is the File’s Owner, when we load the nib, the outlet will get connected to an object in the nib if the outlet with that name on File’s Owner is connected to an object in the nib…

That’s just brilliant. Kudos to whomever at Apple thought of it.

We think we’d go more with “sadistically twisted” than “brilliant” per se — that’s what anyone tasked with maintaining your code would think, almost certainly — but it certainly is creative, yes. Try it out yourself … for enhancing job security, if nothing else!

h/t: 71^2!


If you decide to use this strategy, be warned that you need to set the identifier in InterfaceBuilder to match the table’s reuse identifier — otherwise you will allocate a new instance for every row! Link to article with details can be found here.