UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath: Exception

Viewed 61405

i actually dont see my error:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *CellIdentifier = @"Cell";

  FriendTableViewCell *cell = (FriendTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (cell == nil) {
      cell = [[[FriendTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
      [[NSBundle mainBundle] loadNibNamed:@"FriendTableViewCell" owner:self options:nil];
      cell = friendCell;
  }
  cell.lblNickname.text =  @"Tester";
  return cell;
}

What am i doing wrong? I checked all twice.. but dont see the error.

Thanks for your help!

9 Answers

You're returning friendCell, and it's very likely nil.

Your code looks fine, so make sure you have your Interface Builder file set up right. In FriendTableViewCell.xib, be sure the File's Owner is your table view controller and that you correctly set the cell to be an outlet to friendCell (which I assume is a UITableViewCell).

You are creating a FriendTableViewCell and then ignoring it and setting it equal to (presumably) an instance variable named friendCell.

I assume that you expect friendCell to be set when calling the loadNibNamed method. It apparently is not being set.

So you've got two problems with this code. First, don't allocate a cell twice.

cell = [[[FriendTableViewCell ....
[[NSBundle mainBundle .....
cell = friendCell;

Obviously, the creation of a new cell and assigning it to cell is useless if you are overwriting it with the second call to assignment to cell.

Second, friendCell is probably nil. Make sure the NIB is set up correctly and has the outlets pointing to the right places.

Look here: Loading TableViewCell from NIB

This is Apple's document for this exact subject.

//This is assuming you have tvCell in your .h file as a property and IBOutlet
//like so:
TableViewController.h
@property(nonatomic,retain) IBOutlet UITableViewCell *tvCell;
//Data Source Method...
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

if (cell == nil) {

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

    cell = tvCell;

    self.tvCell = nil;

use the loadNibNamed:owner:options method to load a cell in a nib. Set the cell instance to your nib object, then set the nib object to nil.

Read the rest of the documentation that I've linked to know how to access subviews inside your cell.

Related