UITableView dequeueReusableCellWithIdentifier Theory
Solution 1:
dequeueReusableCellWithIdentifier:
only returns a cell
if it has been marked as ready for reuse. This is why in almost every cellForRowAtIndexPath:
method you will see something like
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (nil == cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:CellIdentifier];
}
// Do something to cell
return cell;
In effect, enough rows will be allocated to fill the visible part of the tableview
(plus one or two more). As cells scroll
off screen, they are removed from the table
and marked as ready for reuse
. As the queue of "available cells" grows, your line that asks for a dequeued cell
will start obtaining a cell
to use, at which point you will not have to allocate anymore.
Solution 2:
The code for deqeueueReusableCellsWithIdentifier:
will look something like this:
(Taken from one of my own projects where I do something similar with views/pages in a paged scroll view)
- (UIView*) dequeueReusablePage
{
UIView* page = [reusablePages_ anyObject];
if (page != nil) {
[[page retain] autorelease];
[reusablePages_ removeObject: page];
}
return page;
}
So it keeps a simple NSMutableSet
with reusable objects.
When cells scroll off the screen and are not longer visible, they are put in this set.
So you start with an empty set and the set will only grow if you actually have more data to show then is visible on the screen.
Used cell scrolls off the top of the screen, is put in the set, then taken for the cell that appears at the bottom of the screen.