Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the mechanism used by SDWebImage when used in a UITableView

This question is for my understanding as my code is working fine. I have looked inside SDWebImage, but it's fairly large and I can't pinpoint how the mechanism I'm questioning works.

OK, let's say I have a tableview full of UIImageViews (one inside each cell), and I call the SDWebImage Category/Extension on each of them to go and lazy load an image from the web.

What mechanism is employed to update the cell as it's on screen with the newly downloaded image, without reloading the tableview?

I ask this as I was surprised to see that when using SDWebImage Extension each of my cells' imageViews image popped into existence as soon as it's corresponding image had downloaded.

I was under the impression that I'd have to reload the tableView, but instead each cells imageView 'automagically' updated when the image was available!

How does this work? Does SDWebImage keep a reference to each cell/imageView it's working with?

like image 380
Woodstock Avatar asked Dec 17 '17 11:12

Woodstock


1 Answers

SDWebImage inserts the loaded image into the UIImageView instance on which the load has been queried.

With UITableViewCell you have to be a bit tricky to avoid non-relevant images in your cells, here is why:

  1. Imagine you requested the image for URL of the first item (firstURL) on the topmost visible cell.
  2. You scroll down your table, and following happens:
    • the former topmost cell gets reused and appears on the bottom of the table.
    • the image is queried for URL of the last cell (lastURL).
  3. firstURL loading completed, and corresponding image is inserted into the image view of the last cell, because it was the image view for which firstURL loading has been queried.
  4. lastURL loading completed, and corresponding image is inserted into the image view of the last cell.

Steps 3 and 4 might look like fast blink in the image view.

To avoid that, you need to address the cancellation of the previous download in prepareForReuse method implementation of the UITableViewCell subclass.

e.g.

- (void)prepareForReuse {
    [super prepareForReuse];
    [self.imageView sd_cancelCurrentImageLoad];
    self.imageView.image = <placeholder image>;
}
like image 94
Eugene Dudnyk Avatar answered Oct 10 '22 00:10

Eugene Dudnyk