dequeueReusableCellWithIdentifier如何工作?

Nie*_*gen 5 iphone uitableview ios

我想要一些精确的dequeueReusableCellWithIdentifier:kCellIdentifier.如果我理解得很好,下面的NSLOG应该打印一次.但事实并非如此.那么dequeueReusableCell有什么意义呢?它只对定制单元有效吗?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCellIdentifier = @"UITableViewCellStyleSubtitle3";


    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
    if (cell == nil)
    {
        NSLog(@"creation of the cell");
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCellIdentifier] autorelease];
    }

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = [[self.table objectAtIndex:indexPath.row] objectForKey:kTitleKey];


    [cell setBackgroundColor:[UIColor colorWithWhite:1 alpha:0.6]];
    return cell;
}
Run Code Online (Sandbox Code Playgroud)

Mic*_*gle 11

它只在初始化的单元格移出屏幕时才起作用.

例如,假设您有一个表格视图,在屏幕上显示十个单元格,但总共有一百行.首次加载视图并填充表视图时,将初始化十个单元格(因此多个 NSLog 语句).当您开始向下滚动时,从屏幕顶部消失的单元格将被放入重用队列中.当需要绘制从底部出现的新单元时,它们从重用队列中出列,而不是初始化新实例,从而保持内存使用率下降.

这也是为什么在if (cell == nil)条件之外配置单元属性的重要性.


Mat*_*uch 5

开始滚动您的tableview,您应该看到日志消息不再出现.

如果你有一个高度为1000像素的tableview,并且每个单元格的高度为100像素,你将看到11次日志消息.
因为11是同时可见的最大细胞数量.
它是11而不是10,因为当你向下滚动一点时,将有9个完全可见的单元格和2个仅部分可见的单元格.