2

我似乎无法开始dequeueReusableCellWithIdentifier工作。

我需要为 IOS 4 构建一个项目,所以我不能使用情节提要,但我正在使用 ARC。

假设我有 2 个部分,每个部分有 1 行。

查看下面的代码,我使用 strong 属性来传递所有权,因为 ARC 会插入“自动释放”代码。

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

     MainTableCell *cell = (MainTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

     if (cell == nil) 
     {
          self.retainedCell = [[MainTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
     }

     [self configureCell:cell atIndexPath:indexPath];

     return cell;
}

但是,对于每一行,每次调用该函数时,单元格始终为零(因此分配了一个新的 MainTableCell)。细胞永远不会被重复使用。

这不是什么大问题,除非我以编程方式调用 tableView:cellForRowAtIndexPath:,这意味着我每次都会获得一个新分配的单元格,而不是现有的单元格。

我能看到的唯一方法是将单元格添加到 NSMutableArray。

我现在缺少dequeueReusableCellWithIdentifier什么吗?

谢谢!

编辑 我正在使用下面的代码来获取单元格。如前所述,它正在创建一个新单元格,而不是重新使用应该已经制作+保留的单元格。我不需要为所有行调用 reloadData,只需更改一个特定的行。

MainTableCell *cell = (MainTableCell *)[self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
[self configureCell:cell atIndexPath:indexPath];
4

1 回答 1

3

您碰巧正在使 MainTableCell 出队,然后您继续检查它是否为 nil,此时您使用完全不同的 var 来分配表格单元格。有没有搞错?尝试这个:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"TableCellIdentifier";
    MainTableCell *cell = (MainTableCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) 
    {
        cell = [[MainTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    [self configureCell:cell atIndexPath:indexPath];

    return cell;
}
于 2012-05-18T05:18:54.770 回答