Loading a Reusable UITableViewCell from a Nib

Solution 1:

Actually, since you are building the cell in Interface Builder, just set the reuse identifier there:

IB_reuse_identifier

Or if you are running Xcode 4, check the Attributes inspector tab:

enter image description here

(Edit: After your XIB is generated by XCode, it contains an empty UIView, but we need a UITableViewCell; so you have to manually remove the UIView and insert a Table View Cell. Of course, IB will not show any UITableViewCell parameters for a UIView.)

Solution 2:

Just implement a method with the appropriate method signature:

- (NSString *) reuseIdentifier {
  return @"myIdentifier";
}

Solution 3:

Now, in iOS 5 there is an appropriate UITableView method for that:

- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier

Solution 4:

I can't remember where I found this code originally, but it's been working great for me so far.

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"CustomTableCell";
    static NSString *CellNib = @"CustomTableCellView";

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:CellNib owner:self options:nil];
        cell = (UITableViewCell *)[nib objectAtIndex:0];
    }

    // perform additional custom work...

    return cell;
}

Example Interface Builder setup...

alt text

Solution 5:

Look at the answer I gave to this question:

Is it possible to design NSCell subclasses in Interface Builder?

It's not only possible to design a UITableViewCell in IB, it's desirable because otherwise all of the manual wiring and placement of multiple elements is very tedious. Performaance is fine as long as you are careful to make all elements opaque when possible. The reuseID is set in IB for the properties of the UITableViewCell, then you use the matching reuse ID in code when attempting to dequeue.

I also heard from some of the presenters at WWDC last year that you shouldn't make table view cells in IB, but it's a load of bunk.