我正在研究一个iPhone应用程序,它具有一个非常大的UITableView,其中包含从Web获取的数据,所以我正在试图优化它的创建和使用。
我发现dequeueReusableCellWithIdentifier非常有用,但是在看到许多使用此源代码的源代码之后,我想知道这个函数的用法是否合适。
人们通常所做:
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"];
// Add elements to the cell
return cell;
这是我做到这一点的方式:
// The cell row
NSString identifier = [NSString stringWithFormat:@"Cell %d", indexPath.row];
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell != nil)
return cell;
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:identifier];
// Add elements to the cell
return cell;
不同之处在于人们对每个单元使用相同的标识符,所以出列一个只会避免分配一个新的。
对我来说,排队的重点是给每个单元格一个唯一的标识符,所以当应用程序要求已经显示的单元格时,不需要添加分配和元素添加。
“共同”的方法ceils表的内存使用的确切数目也显示,whislt我使用的方法似乎是因为它使所有的计算单元,以理想的速度,但可引起大内存消耗(除非队列有内部限制)。
是否取决于他的需求,它是否取决于开发者?
发布于 2018-04-16 16:02:12
目的dequeueReusableCellWithIdentifier
是使用更少的内存。如果屏幕可以放置4个或5个表格单元格,那么即使表格有1000个条目,只需要在内存中分配4或5个表格单元格即可。
第二种方式没有重用。第二种方法比使用表格单元格阵列没有什么优势。如果你的表有1000个条目,那么你将在内存中分配1000个单元。如果你打算这样做,你可以把它们放在一个数组中,然后用行号索引数组并返回单元格。对于固定单元格的小型表格,这可能是一个合理的解决方案,对于动态或大型表格,这不是一个好主意。
发布于 2018-04-16 16:38:52
至于小区标识符 - 不是使用“小区”作为标识符,而是使用像OP这样的唯一标识符,可以使用“类型标识符”吗?例如,如果我的表格有3种类型的单元格 - 一种具有非常复杂的子布局,一种是刚刚使用Style1
,另一种使用Style2
,我应该单独标识这三种,然后在出现出现时重建它们nil
。
例如:
-(UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath{
NSString* ident = @"";
if(indexPath.section == 0) ident= @"complicated";
if(indexPath.section == 1) ident= @"style1";
if(indexPath.section == 2) ident = @"style2";
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:ident];
if(cell == nil){
if(ident == @"complicated"){
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:ident] autorelease];
// do excessive subview building
}
if(ident == @"style1"){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyle1 reuseIdentifier:ident] autorelease];
}
if(ident == @"style2"){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyle2 reuseIdentifier:ident] autorelease];
}
}
if(ident == @"complicated"){
// change the text/etc (unique values) of our many subviews
}
if(ident == @"style1"){
[[cell textLabel] setText:@"Whatever"];
}
if(ident == @"style2"){
[[cell textLabel] setText:@"Whateverelse"];
}
return cell;
}
(这段代码可能不会运行,因为我在这里写了它,但希望你明白。)
如果他们想要所有的标识符,我不认为苹果会创建带有标识符的整个可重用单元的想法"cell"。
https://stackoverflow.com/questions/-100008119
复制相似问题