Nick Klockenga

Correctly Reusing UITableViewCell from xib

I've seen a lot of bad code around creating a reusable UITableViewCell in the UITableView data source delegate. So I thought I'd share what I assume to be the right way to reusable table view cells when loading from a nib.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
      UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
      if (cell == nil)
      {
          NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"cell" owner:self options:nil];
          cell = [topLevelObjects objectAtIndex:0];
          [tableView registerNib:[UINib nibWithNibName:@"cell" bundle:nil] forCellReuseIdentifier:@"cell"];
      }

      [cell setup];

      return cell;
}

The 'registerNib: forCellReuseIdentifier: ' method is the part that is often missing in code snippets on stackoverflow. This has been in the documentation since iOS 5. In fact, it might even make sense to register the nib in the viewDidLoad and forgo the if check all together.