Doug Smith
Doug Smith

Reputation: 29316

Why is using numberOfRowsInSection causing a never ending loop in my app?

I was having issues with my cell background image being distorted, and after having it answered I then went to implement the solution which basically consisted of shortening the height of the specific offending cells (that automatically had height added to them). I did this as follows:

- (CGFloat)tableView:(UITableView *)tableView 
  heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat standardHeight = 44.0;

    if ([tableView numberOfRowsInSection:indexPath.section] == 1) {
        standardHeight -= 2;
    }

    return standardHeight;
}

However, every time I run that, I get caught in some sort of execution loop, where the app keeps bouncing back between the first line of that method and the start of the if statement until it crashes.

Video: http://f.cl.ly/items/2F1E3r2A2p0y1b2j3R14/debug.mov

However, if I use something like this (one of the answers in the previous thread) it seems to work:

- (CGFloat)tableView:(UITableView *)tableView 
  heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat rowHeight = 44.0f;
    if (indexPath.row == 0) {
        rowHeight -=1;
    }
    return rowHeight;
}

What am I doing wrong? I just can't figure it out.

Upvotes: 2

Views: 544

Answers (2)

Cezar
Cezar

Reputation: 56322

The problem here is that you shouldn't rely on one datasource/delegate method to provide data to the other. What is essentially happening is that you are asking your tableView how many rows it has in a section, when you should be getting this information from your model (which is from where numberOfRowsInSection: should be getting it from as well)

All your datasource methods should just return data directly from the model, since your tableView may ask your datasource for data on unexpected times. That is true not only for UITableView but for all datasource based views, such as UICollectionView for example.

Upvotes: 6

Andrew
Andrew

Reputation: 1106

Instead of calling the numberOfRowsInSection: method from the tableView, you can do this:

if ([self tableView:tableView numberOfRowsInSection:indexPath.section] == 1) {
    standardHeight -= 2;
}

This will be safe because it only invocates your own code.

Upvotes: 1

Related Questions