Understanding the mechanism used by SDWebImage when used in a UITableView

This question is for my understanding, since my code is working fine. I looked into SDWebImage, but it is quite large, and I can’t determine exactly how the mechanism I'm asking about works.

OK, let's say I have a table view full of UIImageViews (one inside each cell), and I call the SDWebImage category / extension on each of them to go and be lazy to download the image from the Internet.

What mechanism is used to update a cell, like on a screen, with a recently loaded image without reloading the table?

I ask about this, because I was surprised to see that when using the SDWebImage extension, each image image of my cell images appeared immediately after loading the corresponding image.

I got the impression that I would have to reload the tableView, but instead, each imageView element "automatically" updates when the image is available!

How it works? Does SDWebImage support a link to every cell / imageView that it works with?

+5
source share
2 answers

SDWebImage inserts the downloaded image into the UIImageView instance for which the download was requested.

With UITableViewCell you have to be a little tricky to avoid unnecessary images in your cells, here's why:

  1. Imagine you requested an image for the URL first element ( firstURL ) in the topmost visible cell.
  2. You scroll the table down and the following happens:
    • The former top cell is reused and appears at the bottom of the table.
    • An image is requested for the URL last cell ( lastURL ).
  3. firstURL completed, and the corresponding image is inserted into the image view of the last cell, as it was an image view for which firstURL loading firstURL .
  4. lastURL loading lastURL completed and the corresponding image is inserted into the image representation of the last cell.

Steps 3 and 4 may look like a quick blink when viewing an image.

To avoid this, you need to refer to prepareForReuse previous load in the prepareForReuse method of the prepareForReuse subclass.

eg

 - (void)prepareForReuse { [super prepareForReuse]; [self.imageView sd_cancelCurrentImageLoad]; self.imageView.image = <placeholder image>; } 
+3
source

If you reference UIImageview in a UITableviewCell, then you can verify that SDWebImage is a type of UIImageView class, so there is no need to describe which image refers to the loaded image, as its self-determination

Let me show you one day. as we request the image inside the cell as follows.

 [cell.imgBrand sd_setImageWithURL:url completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if (error != nil) { NSLog(@"%@", [error localizedDescription]); } }]; 

When the first line is executed, it will call the method inside the UIImageView+WebCache.h . as you can see this UIImageView class itself

 @implementation UIImageView (WebCache) 

Class for SDWebCache UIImageView

+3
source

Source: https://habr.com/ru/post/1274126/


All Articles