How does dequeueReusableCellWithIdentifier work: work?

I would like to know a little about dequeueReusableCellWithIdentifier:kCellIdentifier . If I understand well, then in the future, NSLOG should print only once. But this is not so. So what is the meaning of dequeueReusableCell? Is it efficient only with a 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; } 
+3
source share
2 answers

Start scrolling in your table view and you will see that the log message is no longer displayed.

if you have a table view with a height of 1000 pixels and each cell has a height of 100 pixels, you will see a log message 11 times.
Because 11 is the maximum number of cells that are visible at the same time.
This is 11, not 10, because when you scroll down a bit, there will be 9 cells that are fully visible and 2 cells that are only partially visible.

+4
source

It only starts if the initialized cells are moved off the screen.

For example, let's say you have a table view that displays ten cells on the screen, but contains only 100 rows. When the view is first loaded and the table view is populated, ten cells will be initialized (hence several NSLog statements). When you start to scroll down, cells that disappear at the top of the screen are placed in the reuse queue. When new cells appearing below should be drawn, they are unloaded from the reuse queue instead of initializing new instances, thereby reducing memory usage.

This is why it is important to set the properties of your cell outside the if (cell == nil) condition.

+7
source

All Articles