views:

18

answers:

2

Im not sure why, but my UITableView, which isnt anything fancy, is showing repeating rows when it shouldnt be.

It seems that the rows that get added when the user scrolls (i.e. the rows that are off the screen to start with) are getting the data for the wrong row index. Its almost like when a new cell is de-queued, it's using a cell that 'was' used, but wasn't cleaned up correctly.

Do you need to 'clean up' cells that are de-queue so that new cells dont use cells that are already created?

my code is as below:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CustomCellIdentifier = @"CustomCellIdentifier";

    MyDayCell *cell = (MyDayCell *)[tableView 
                                      dequeueReusableCellWithIdentifier: CustomCellIdentifier];

    if (cell == nil) { 
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"MyDayCell" owner:self options:nil];

        for (id oneObject in nib) 
            if ([oneObject isKindOfClass:[MyDayCell class]])
                cell = (MyDayCell *)oneObject;

    } 

    NSUInteger section = [indexPath section];
    NSUInteger row = [indexPath row]; 
    NSArray *thisSectionItems = (NSArray*)[self.listData objectForKey: [[NSNumber alloc] initWithInt:section]];
    MyDayDetails *rowData = [thisSectionItems objectAtIndex:row]; 

    //setup my cells data here...

    return cell;
}

Is there anything wrong with this code?

has anyone seen anything like this before?

A: 

I think i have solved it, do I just need to add an else statement to the if (cell == nil) block which cleans up the cells populated values?

Is this the correct way to go about doing this?

Mark
Aren't you changing the values in your "//setup my cells data here..." section anyways? I don't think you'd need to explicitly clean up the populated values first.
Thomas Müller
sort of, im just setting what needs to be set, not cleaning up old information.
Mark
+1  A: 

Cells are supposed to be reused. If you want to turn that off, turn off cell reuse.

Your problem is actually in the code you didn't include.

//setup my cells data here...

This code is responsible for completely loading every aspect of the cell that varies between the rows in your table. That data that's showing up more than once? You need to set it in cases where you have it, or clear it if you don't.

For instance:

cell.textLabel.text = str ? str : @"";

In that way, the same few cells are used over and over again, and table cells don't need to be set up and destroyed frequently.

(As I mentioned, you can turn off cell reuse. But you should make this work.)

Steven Fisher
ok so that makes sense, and is pretty much what I have implemented, thanks for that
Mark