我在我的表视图中使用了“自调整大小的单元格”,当插入单元格时,使用‘insert insertRowsAtIndexPaths:withRowAnimation:’的单元格有时会被取消分配,但我已经为这些单元格设置了reuseIdentifier。当我滚动表视图时,单元格没有被解除分配。
为什么要这样做?
这是我得到单元格的代码:
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;
}发布于 2018-01-08 20:45:24
重用意味着当单元格离开屏幕时,它不会被释放,但tableView将保留它,以便将其用于将要显示的那些行。因此,当您将单元出队时,不会实例化新的单元实例,而是返回屏幕上不再显示的现有实例。这提供了更好的性能,因为创建对象是一个相当苛刻的操作。
此外,如果您使用dequeueReusableCell(withIdentifier:for:)而不是dequeueReusableCell(withIdentifier:),您可以获得更好的性能,因为在某些情况下甚至不必重新绘制单元格。
这个故事的寓意是:它们不会被释放,因为你想要它们被重用。为了重用,它们必须存在。你不必担心保留周期。
附注:如果问题是您希望在信元进入重用队列时得到通知(因此它等待重用),请按照LGP的建议使用prepareForReuse。这可以在单元格执行一些重量级操作时使用,但它不在屏幕上,因此您可以取消操作以尽快释放资源。
但是,在大多数情况下,您可以在cellForRow中从头配置单元格-只需记住,除非在prepareForReuse中清除了单元格的内容,否则必须确保重置所有内容。例如,如果您有一个显示可选字符串的标签,那么当在没有此字符串的新行中重用时,该标签将被设置为旧的标签。
发布于 2018-01-08 21:12:28
如前所述,当重用时,单元不会被释放。要在重用的单元格中执行清理,可以使用另一种可用于UITableViewCell对象的方法,称为-(void)prepareForReuse;,它将在从dequeueReusableCellWithIdentifier:方法返回单元格之前被调用。
如果覆盖prepareForReuse方法,不要忘记调用超类方法。
https://stackoverflow.com/questions/48150529
复制相似问题