开发者

How does dequeueReusableCellWithIdentifier: work?

I would like some precision about the deq开发者_如何学PythonueueReusableCellWithIdentifier:kCellIdentifier. If I understand well, the hereunder NSLOG is supposed to print just once. But it doesn't. So what is the point of dequeueReusableCell ? Is it only efficient with custom cell ?

- (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;
}


It only comes into play when initialized cells are moved off screen.

For instance, say you have a table view that displays ten cells on screen, but has a hundred rows in total. When the view is first loaded and the table view populated, ten cells will be initialized (hence the multiple NSLog statements). When you start to scroll down, the cells that disappear off the top of the screen are placed into the reuse queue. When the new cells appearing from the bottom need to be drawn they are dequeued from the reuse queue instead of initialising new instances, thereby keeping memory usage down.

This is also why it's important that you configure the properties of your cell outside of the if (cell == nil) condition.


Start to scroll on your tableview and you should see that the log message doesn't appear anymore.

if you have a tableview that has a height of 1000 pixels, and each cell has a height of 100 pixels you will see the log message 11 times.
Because 11 is the maximum amount of cells that are visible at the same time.
It's 11 and not 10 because when you scroll down a little there will be 9 cells that are fully visible and 2 cells that are only partial visible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜