简体   繁体   English

不重复的UITableView单元格

[英]UITableView cell that does not repeat

This is probably a very simple question but I'm a little confused how this should be done right. 这可能是一个非常简单的问题,但我有点困惑如何正确地做到这一点。 I read that I need to remove this line of code: 我读到我需要删除这行代码:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

But then how do I check if the cell is not nil? 但是,我如何检查细胞是否为零? The complete code I use is below. 我使用的完整代码如下。 If someone could also please explain what the purpose this line: 如果有人也可以请说明这条线的目的是什么:

static NSString *CellIdentifier = @"Cell";

Entire code: 整个代码:

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

You are using it right in the code you posted. 您正在使用它发布的代码中使用它。 The reason for having the static type modifier is to prevent the variable to be created and initialized each time the method is invoked. 拥有静态类型修饰符的原因是为了防止每次调用方法时都创建和初始化变量。 "Normal" variables are automatically created and deleted in each method, and you could in fact do this: 在每种方法中自动创建和删除“正常”变量,您实际上可以这样做:

auto NSString* cellId = @"CellId";

The auto type modifier is default (compiler adds it) and to save typing people do not add it. auto类型修饰符是默认的(编译器添加它),为了保存键入,人们不会添加它。 By putting static in front of the type you change this behavior so that the variable is initialized only once, when the program starts. 通过将static放在类型前面,可以更改此行为,以便在程序启动时仅将变量初始化一次。 It is called static because the data in the variable with the type modifier static is not automatically removed from the stack each time the method is invoked...it is static/does not change. 它被称为static因为每次调用方法时,带有类型修饰符static的变量中的数据都不会自动从堆栈中删除...它是静态的/不会更改。 Hence the name. 由此得名。

Since you are using the cell id over and over, it have a tiny performance benefit to initialize it only once instead of create/delete the variable each time the method is invoked. 由于您一遍又一遍地使用单元格id,因此每次初始化它只有一次而不是在每次调用方法时创建/删除变量时,它具有很小的性能优势。 This could be especially true for tables with a lot of cells. 对于具有大量单元格的表格尤其如此。 However I have never seen the difference between using auto and static variables, but that is at least the idea behind it. 但是我从来没有看到使用auto变量和static变量之间的区别,但这至少是它背后的想法。

You are not supposed to remove the [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 你不应该删除[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; line. 线。 You need that to be able to dequeue table view cells from the tableview. 您需要能够从tableview中出列表视图单元格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM