iphone - dequeueReusableCellWithIdentifier 不适用于 ARC 和 IOS 4

标签 iphone ios4 automatic-ref-counting

我似乎无法让 dequeueReusableCellWithIdentifier 工作。

我需要为 IOS 4 构建一个项目,因此无法使用 Storyboard,但我正在使用 ARC。

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

看看下面的代码,我使用强属性来传递所有权,因为 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;
}

但是,对于每一行,每次调用该函数时,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];

最佳答案

您碰巧正在使 MainTableCell 出队,然后您继续检查它是否为零,此时您使用完全不同的 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;
}

关于iphone - dequeueReusableCellWithIdentifier 不适用于 ARC 和 IOS 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10647054/

相关文章:

ios - 开发、生产、开发配置文件和分发配置文件之间的区别?

iphone - 使用私有(private) iOS BluetoothManager 框架进行设备配对

rust - 当我克隆一个内部有 Arc 的结构时会发生什么?

macos - drawInRect 保留 NSImage 直到将来的某个时刻?

iphone - iOS 中的 SQLite 表现奇怪

iphone - 在 NSTimers 中编写代码而不是选择器?

iphone - 配置文件 hell

iphone - 滚动 uitableview 时 UIProgressView 被隐藏

ios - 关于 ARC 功能

iphone - 如何在 Core Plot Y 轴上显示整数而不是小数?