TheBinaryhood
TheBinaryhood

Reputation: 231

When do custom table view cells dealloc?

I was under the impression that table view cells never got dealloced until the app crash because you are able to resuse them. But when I was profiling my table view, I realized that something was calling dealloc on my custom cell. What exactly dealloc's custom cells and can I stop it?

Upvotes: 3

Views: 3793

Answers (3)

Jilouc
Jilouc

Reputation: 12714

Using the common "reuse" pattern:

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellId = @"Foo";
    UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId]
                autorelease];
    }
    // update the cell content
    return cell;
}

The table view creates as many cells as required to fill the its frame height.
When disappearing from screen they are removed from the view and put in the reuse queue, thus not deallocated.

All the cells are dealloc'd when the tableView is dealloc'd and some cells may be dealloc'd when you number of rows changes (say you had 20 cells before and only 2 after update).

You might be tempted to get rid of cells reuse but you would lose all the magic done behind to keep a low memory footprint and to have a smooth scrolling experience.

Upvotes: 4

Peter DeWeese
Peter DeWeese

Reputation: 18333

Table views create and shed cells as needed. This is to allow for very long lists to be scrolled through without storing them all in memory. A virtually infinite scrollable list is possible. A convenient way to retain your custom cells for the table view's lifespan is to add them to a mutable array upon creation. Before creating, look in the array to see if it already exists.

Upvotes: 0

drewh
drewh

Reputation: 10167

The semantics of the dequeueReusableCellWithIdentifier: selector are opaque (as far as I know). If you want complete control of your table view cells, don't use that selector to get a cell: just construct a new one or use your own pool for reuse.

Upvotes: 1

Related Questions