我正在开发一款iPhone应用程序,它有一个非常大的UITableView,其中包含从网络上获取的数据,因此我正在尝试优化其创建和使用.
我发现这dequeueReusableCellWithIdentifier非常有用,但是在看到很多使用它的源代码之后,我想知道我对这个函数的用法是不是很好.
这是人们通常做的事情:
UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"Cell"];
// Add elements to the cell
return cell;
Run Code Online (Sandbox Code Playgroud)
这就是我做的方式:
// 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;
Run Code Online (Sandbox Code Playgroud)
不同之处在于人们对每个单元使用相同的标识符,因此只出列一个标识符可以避免分配新标识符.
对我来说,排队的重点是给每个单元格一个唯一的标识符,所以当应用程序要求它已经显示的单元格时,既不需要进行分配也不进行元素添加.
很好,我不知道哪个是最好的,"常用"方法将表的内存使用量提升到它显示的确切数量的单元格,而我使用的方法似乎有利于速度,因为它保留所有计算的单元格,但可能导致大内存消耗(除非队列有内部限制).
我这样用它错了吗?或者仅仅取决于开发人员,取决于他的需求?