UITableView 数据源必须从 tableView:cellForRowAtIndexPath 错误返回一个单元格 [英] UITableView dataSource must return a cell from tableView:cellForRowAtIndexPath error
本文介绍了UITableView 数据源必须从 tableView:cellForRowAtIndexPath 错误返回一个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这段代码中遇到了那个错误.你能帮我找出原因吗.
I am getting that error with this piece of code. Can you help me figure out why.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"CustomerCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Restaurant *restaurant = [self.restaurants objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[NSString stringWithFormat:@"%@ %@",restaurant.Name,restaurant.Address]];
return cell;
}
推荐答案
你的代码的问题是 dequeueReusableCellWithIdentifier:
并不总是返回一个有效的单元格;有时,它返回 nil
.在这种情况下,您需要分配一个新的单元实例,然后以通常的方式对其进行初始化.按照目前的情况,如果从 dequeueReusableCellWithIdentifier:
方法返回一个,您的方法将返回 nil
.
The problem with your code is that dequeueReusableCellWithIdentifier:
does not always return you a valid cell; sometimes, it returns nil
. In such cases you need to allocate a new instance of your cell, and then initialize it the usual way. As it currently stands, your method would return nil
if one is returned from the dequeueReusableCellWithIdentifier:
method.
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyle1 reuseIdentifier:CellIdentifier];
}
这篇关于UITableView 数据源必须从 tableView:cellForRowAtIndexPath 错误返回一个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文