iOS 5 introduced a new API that you can use to register a NIB to be used with cells.

  [self.tableView registerNib:[UINib nibWithNibName:@"RMMenuCell" bundle:nil]
       forCellReuseIdentifier:@"RMMenuCell"];

When you register a nib, the dequeue method is guaranteed to return a cell either by dequeuing or by creating a new cell.

So in your tableview’s cellForRowAtIndexPath, no longer have to write something like this

 
if (cell == nil) {
 
		NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyCustomCell" owner:self options:nil];
		cell = (MyCustomCell*)[nib objectAtIndex:0];
	}

However, there is a grave pitfall that you should be aware of.
Looks like, a nib that your register for a given identifier should contains no more than one top level object, failing which, the dequeue method will crash

Redmart xcodeproj  RMSlidingMenuViewController m

So why did my nib file contain more than two top level objects? I have a habit of adding a UIImageView to my cell XIB and connecting the selectedBackgroundView of the cell to this image view as shown below.

Cell with two top level objects

Apparently, nibs like this with two top level objects isn't supported with registerNib:forCellReuseIdentifier method.

I'm not sure if this is a bug, or an expected behaviour. The documentation doesn't explain it either. If you think this behaviour is wrong/unexpected, duplicate radar://11962233

Update:
Apple replied that this is an expected behaviour.


Mugunth

Follow me on Twitter

  • http://twitter.com/altimac Aurelien Hugele

    This is not an expected behaviour !
    how are we supposed to customize selectedBackgroundView then ? allocating a backgroundView for each cell is counter efficient . I’m stumped with this “new” method