user4234
user4234

Reputation: 1527

Is there any reason why we don't simply declare cellForRowAtIndexPath like this:

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [self.tableView cellForRowAtIndexPath:indexPath];
    return cell.bounds.size.height;
}

What would be the disadvantage?

I changed that from

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    return cell.bounds.size.height;
}

Upvotes: 0

Views: 268

Answers (2)

rob mayoff
rob mayoff

Reputation: 385900

As rmaddy points out, you can't use the first version because -[UITableView cellForRowAtIndexPath:] can cause the table view to send you tableView:heightForRowAtIndexPath: again, resulting in infinite recursion.

If you are using a static set of cells, with one cell preallocated for each row of the table, then the second version is fine.

If you are dynamically creating cells for rows, the second version will end up draining your table view's reuse queue and then creating another cell for every row, because tableView:cellForRowAtIndexPath: returns an autoreleased object. None of these cells will be deallocated until the end of the run loop, so in addition to the time cost of creating and destroying all of these cells, you're also using memory proportional to the number of rows in your table. If you want to do it that way, and you have a lot of rows, you might want to use an explicit autorelease pool:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    @autoreleasepool {
        UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
        return cell.bounds.size.height;
    }
}

Upvotes: 2

rmaddy
rmaddy

Reputation: 318884

Normally you would want to get a cell from the table like you do in the 1st bit of code. But in this case you can't. If you try, you will end up with a recursive call between cellForRowAtIndexPath and heightForRowAtIndexPath.

If you must get a cell from the heightForRowAtIndexPath method, you must NOT ask the table for the cell.

Upvotes: 2

Related Questions