views:

424

answers:

2

I have a class which extends UITableViewCell. For the purpose of this exercise, let's call it "CustomCell". In CustomCell, I have a UIImageView IBOutlet setup. The image instance name in this case is myImage. I wish to display this image based on certain criteria that's coming back from a server. That data is a dictionary which in this exercise we'll call "serverData". At first, the UITableView renders just fine with the UIImageView showing up in cells which it should. The problem occurs when I start scrolling the actual UITableView, the image gets lost. Somehow it's not properly being either cached or dequeued. Not sure where the problem is or how to better improve on this code. Here's an excerpt:

- (UITableViewCell *)tableView:(UITableView *)tableView
 cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
 static NSString *CustomCellIdentifier = @"CustomCellIdentifier";
 CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CustomCellIdentifier];
 if (cell == nil)  {
  NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" 
              owner:self options:nil];

  cell = (CustomCell *)[nib objectAtIndex:0];
  cell.selectionStyle = UITableViewCellSelectionStyleNone;
 }      

  NSDictionary *serverData = myData // previously defined.
  if ([[serverData valueForKey:@"foo"] isEqualToString:@"0"]) 
   cell.myImage.hidden = YES;
  cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
  return cell;
}
+4  A: 

For memory reasons UITableView reuses cells when scrolling (e.g the dequeueReusableCellWithIdentifier) call.

What this means is that the cell you receive could have been configured in anyway that is valid for use with that identifier so you must reset all these properties.

In your case I suspect you are being given a cell with an image that had been hidden so this will fix it:

  NSDictionary *serverData = myData // previously defined.
  if ([[serverData valueForKey:@"foo"] isEqualToString:@"0"]) 
    cell.myImage.hidden = YES;
  else
    cell.myImage.hidden = NO;
Andrew Grant
+2  A: 

Remember that your cells are being reused, so you need to reset the cell.myImage.hidden value each time you use that cell

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

            cell = (CustomCell *)[nib objectAtIndex:0];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
    } else {
            cell.myImage.hidden = NO;
    }
nduplessis