ios - TableViewCell 不要重用

标签 ios objective-c uitableview

我在我的 tableview 中使用“Self Sizing Cells”,当插入单元格使用“insertRowsAtIndexPaths:withRowAnimation:”时,单元格有时会被释放,但我已经为单元格设置了 reuseIdentifier。当我滚动 tableview 时,单元格不会被释放。

为什么要这样?

这是我获取单元格的代码:

Class cls = [CWNSessionUtil cellClassForContent:content];
        NSString *reuseIdentifier = [cls reuseIdentifier];

        cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if(!cell)
        {
            cell = [[cls alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        }


+(Class)cellClassForContent:(id)content{
    Class cls;

    if([content isKindOfClass:[MessageEntity class]])
    {
        CubeMessageType type = [((MessageEntity *)content) type];
        switch (type) {
            case CubeMessageTypeFile:
                cls = [CWNFileMessageCell class];
                break;
            case CubeMessageTypeImage:
                cls = [CWNImageMessageCell class];
                break;
            case CubeMessageTypeVideoClip:
                cls = [CWNVideoMessageCell class];
                break;
            case CubeMessageTypeVoiceClip:
                cls = [CWNAudioMessageCell class];
                break;
            case CubeMessageTypeCustom:
                cls = [self cellClassForCustomMessage:content];
                break;
            default:
                cls = [CWNTextMessageCell class];
                break;
        }

    }
    else if([content isKindOfClass:[NSString class]])
    {
        cls = [CWNTipCell class];
    }
    else if([content isKindOfClass:[NSNumber class]])
    {
        cls = [CWNTimeCell class];
    }
    else
    {
        cls = [CWNTipCell class];
    }

    return cls;
}

最佳答案

重用意味着当单元格离开屏幕时,它不会被释放,但 tableView 会保留它以用于将要显示的那些行。因此,当您使一个单元格出队时,不是实例化一个新的单元格实例,而是返回不再显示在屏幕上的现有单元格实例。这提供了更好的性能,因为对象创建是一项要求很高的操作。

此外,如果您使用 dequeueReusableCell(withIdentifier:for:) 而不是 dequeueReusableCell(withIdentifier:),您可以获得更好的性能,因为在某些情况下甚至不必重新绘制单元格。

故事的寓意:它们不会被释放,因为您希望它们被重用。为了重用,它们必须存在。您不必担心保留周期。

P.S.:如果问题是您希望在单元格进入重用队列时收到通知(因此它等待重用),请按照 LGP 的建议使用 prepareForReuse。这可以在单元格执行一些重量级操作但它离开屏幕时使用,因此您可以取消操作以尽快释放资源。

但是,在大多数情况下,您可以在 cellForRow 中从头开始配置单元格 - 请记住,除非您在 prepareForReuse 中清除了单元格的内容,否则您必须确保您重置了所有内容。例如,如果您有一个显示可选字符串的标签,那么当在没有此字符串的新行中重复使用时,标签将设置为旧标签。

关于ios - TableViewCell 不要重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48150529/

相关文章:

ios - 翠鸟图像渲染回收单元

ios - 不继承 UITableViewController 的 UITableView float 表头

ios - 弹出 View Controller 后 UITableViewController 奇怪的行为

ios - 使用 Swift 从 Parse 检索 "createdAt"和 "updatedAt"

ios - Transition 后 TableViewController 几秒不出现

ios - 当我在我的 TableView 上滚动时,有时会在我的 TableView 单元格中设置错误的图像。我怎样才能解决这个问题?

objective-c - dateFromString 返回错误的日期

ios - 在 Swift 中创建一个不规则的 UIButton,其中透明部分不可点击

ios - 如何在核心数据中存储数组(Swift)

iphone - Objective-C - 替换 NSString 中的部分字符串?