views:

501

answers:

3

The following method loads data from an array into custom cells of UITableView. The data is loaded in correctly. However, when I scroll down data in the above cells (the cells not visible) are changed to seemingly random elements in the array.

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

 cellComments=nil;
 cellComments=(FullCommentCell *)[tableView dequeueReusableCellWithIdentifier:FullCommentCell_ID];
 if(cellComments==nil)
 {
  [[NSBundle mainBundle]loadNibNamed:@"FullCommentCell" owner:self options:nil];
 }
 NSString *row = [NSString stringWithFormat:@"#%i",indexPath.row+1];
 [cellComments loadFullComments:[latestFMLComments objectAtIndex:(indexPath.row+1)] withCommentNumber:row];
 //cellComments.userInteractionEnabled=NO;
 return cellComments;
}

I also have the following method that handles when i click on a cell. When the data of a cell changes to some random element in the array - if i click on the cell (which calls the method below) the data in the cell is changed to the right data.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[self tableView:tableView cellForRowAtIndexPath:indexPath];
}

Any ideas why this is happening??

+1  A: 

You are using cached cells, the odds are that you are not resetting the subvview elements of your cell correctly in loadFullComments.

Elfred
what do u mean by resetting the subview elements???
zPesk
A: 

I changed the UITextView to a multi-line UILabel and the everything works now. I am not sure why this makes a difference - but hey it works :)

zPesk
A: 

Elfred has the right idea. When using the

cellComments=(FullCommentCell *)[tableView dequeueReusableCellWithIdentifier:FullCommentCell_ID];

Method call, you need to ensure that any subviews/properties such as labels, images, text, etc. are set every time on that cell. You can't assume that you'll be getting a "fresh" cell with no contents.

For example, when displaying the cell at index 17, the table view might dequeue the reusable cell previously at index 3. This cell will have the same properties as it did when it was in index 3, and it is your responsibility to reset them. (Eg. Changing the text from "I'm Cell 3" to "I'm Cell 17".)

craig
isn't that what im doing with the load comments method - which simply sets the text of the UITextView???
zPesk
Ah, I wasn't aware of what that method did.You may simply want to debug through that method and see how the cells are individually being updated. Cells with old/random data are a classic symptom of reusing cells without properly setting their contents.
craig