views:

32

answers:

2

Hi everyone, i'm now stuck on this problem for days and i haven't been able to figure it out..... I created my project from the navigation based template and it automatically generated a tableview as well. I then added some sections and some rows and tried to fill the rows of the table with simple strings. It all works fine until there are a certain amount of sections and rows the table reaches a certain length. The content of the first row then also appears in the last two rows and i have no idea why... Please HELP!!! Here's my code:

#import "RootViewController.h"


@implementation RootViewController

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Release anything that can be recreated in viewDidLoad or on demand.
    // e.g. self.myOutlet = nil;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}



- (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];
    }

    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.textLabel.text = @"test";
        }
    }

    return cell;
}


- (void)dealloc {
    [super dealloc];
}


@end
A: 

Ok so i think i've got it but i have no idea what was actually happening it was just a coincidence but when i changed the line:

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

to: UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];

it worked... Can somebody pls explain this to me???? ;-)

Christoph v
This should be an edit to the question. Please delete this answer and edit the question instead.
Can Berk Güder
A: 

As you have already noticed, this is due to the way reusable cells work.

However, you really should reuse your cells and always reset their content in tableView: cellForRowAtIndexPath:.

So for example you can do this:

cell.textLabel.text = @"";

if (indexPath.section == 0) {
    if (indexPath.row == 0) {
        cell.textLabel.text = @"test";
    }
}

But normally you would have proper content for each cell.

EDIT: You should really read the Table View Programming Guide, but here's the important excerpt for this question:

The table view’s data source implementation of tableView:cellForRowAtIndexPath: should always reset all content when reusing a cell.

Can Berk Güder