UITableView dataSource必须从tableView:cellForRowAtIndexPath:Exception返回一个单元格

我其实没有看到我的错误:

- (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; } 

我究竟做错了什么? 我检查了两次..但没有看到错误。

谢谢你的帮助!

你正在返回friendCell,这很可能是零。

你的代码看起来很好,所以确保你的Interface Builder文件设置正确。 在FriendTableViewCell.xib中,确保文件的所有者是您的表视图控制器,并且您正确地设置单元格为friendCell(我假设是一个UITableViewCell)的出口。

对我来说,它是这样做的:

 if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } 

UPDATE
将上面的代码放在以下方法中:

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

只需编辑tableViewCell 之前放置它

您正在创buildFriendTableViewCell ,然后忽略它,并将其设置为(大概)一个名为friendCell的实例variables。

我假设你希望friendCell在调用loadNibNamed方法时被设置。 它显然没有被设置。

所以你有这个代码的两个问题。 首先,不要分配一个单元格两次。

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

显然,创build一个新的单元格并将其分配给单元格是没用的,如果用第二个调用来覆盖单元格的话。

其次,friendCell大概是零。 确保NIB安装正确,并将sockets指向正确的位置。

我知道这是一个旧的post,但是,我刚刚遇到这个错误,我发现它非常奇怪,因为应用程序正在testing,所以几天没有新的构build,它做到了这一点,我所做的只是重新启动手机,它解决了它。

我发现这个问题来了,当初始化我的表视图之前尝试创build我的UITableViewCell:

这里在创buildtableView之前注册这个类会导致错误,把它放在后面会修正错误。

 [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:bCellIdentifier]; tableView = [[UITableView alloc] initWithFrame:CGRectZero]; tableView.delegate = self; tableView.dataSource = self; [self addSubview:tableView]; tableView.keepInsets.equal = KeepRequired(0); 

看这里: 从NIB加载TableViewCell

这是苹果公司关于这个确切主题的文件。

 //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; 

使用loadNibNamed:owner:options方法在nib中加载单元格。 将单元格实例设置为您的nib对象,然后将nib对象设置为nil。

阅读我已链接的文档的其余部分,以了解如何访问您的单元格内的子视图。

不要忘记在Interface Builder中设置cell identifier

用这个 ,

 UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:kCellID]; 

我只用这一行就省了几个小时。

确保您的原型单元格的NIB / Storyboard文件中的重用标识符与您称为CellIdentifier的任何内容匹配

  static NSString *CellIdentifier = @"Cell";