views:

410

answers:

3

Good morning all.

I'm having a small crisis with table views in a 3.1 app. I have a table view with some complex tableViewCells being loaded from a nib, and they're not being reused. Feeling it might have something to do with loading them from a nib, I decided to try a simple test project to see if cells are being reused using nothing but the basic apple template code. I started with the Navigation Based Template and here's the code for cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell.
    cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];
    return cell;
}

I have a breakpoint set at the following line, and it's getting called on every pass.

cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]

Setting the reuseIdentifier in the constructor as such:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"] autorelease];
    }

Yields the same result, no cell reuse.

Thanks in advance for any help you can offer!

+1  A: 

The table will usually create and use a few cells (5 or so usually) before it needs to start reusing them. This of course depends on how big they are and how many appear on screen at any given time. Nothing to fret about.

jbrennan
So it doesn't reuse it as it would a template? Seems a bit strange given how much apple talks about reuse.
pzearfoss
It depends. How many rows do you have? The standard table can hold around 8 or so rows visible at once, so they'd need to be unique objects. But if you had say, 20 rows, you'd still only have 8 or so objects, they will just get recycled as they scroll in or out of view.
jbrennan
A: 

Try to make the CellIdentifier static, e.g.

static NSString *CellIdentifier = @"Cell";
MrThys
already static . . .
pzearfoss
Wasn't static in the first version of the question....
MrThys
+1  A: 

I am not sure what you mean by everytime, everytime the app opens ?

Run the code with object allocation tool and look at the graph for object allocations as you scroll through the tableview . If object allocations are increasing linearly even after few scrolls . Then you have a problem.

Surya
Great advice, thank you!
pzearfoss