Search code examples
iostableviewreusability

flashing images tableview reuse bug see the video link -->http://www.youtube.com/watch?v=jwEsqjc9sNc&feature=youtu.be


here's the code : i am downloading image from my core data on background and put it on my image view.

static NSString *cellIdentifier = @"Pubs Cell";
PubsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

Pub *current = [self.fetchController objectAtIndexPath:indexPath];

cell.name.text = current.name;
cell.description.text = current.descriptionText;
cell.description.backgroundColor = [UIColor clearColor];
cell.description.editable = NO;
dispatch_queue_t queue = dispatch_queue_create("image_queue", NULL);
dispatch_async(queue, ^{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",current.photo]]];
    dispatch_async(dispatch_get_main_queue(), ^{

        cell.pubImage.image = [UIImage imageWithData:data];
    });
});
cell.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"light1.jpg"]];

return cell;

any ideas how to fix that? thanks in advance.


Solution

  • You need to set the image to nil before you start the async loading-task:

    // removing the old image from the reused tablecell
    cell.pubImage.image = nil;
    
    // load image asynchronously
    dispatch_queue_t queue = dispatch_queue_create("image_queue", NULL);
    dispatch_async(queue, ^{
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",current.photo]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.pubImage.image = [UIImage imageWithData:data];
        });
    });
    

    This is because loading an image takes some time so you see the old one since tablecells are reused when available.