IOS delays loading pictures in Cell in TableView
In TableView, delayed loading of images is the content to be introduced in this article. We often use tableView to display many entries, and sometimes we need to display images. However, retrieving all images from the server at one time wastes traffic on the user, which is also a burden on the server. It is best to load images as needed, that is, when the user wants to browse the entry and then load it, many entries will be displayed in tableView.
Sometimes images need to be displayed, but retrieving all images from the server at a time wastes user traffic, which is also a burden on the server. it is best to load as needed, that is, when the user wants to browse the entry, then load its image.
Rewrite the following method:
- -(Void) tableView :( UITableView *) tableView willDisplayCell :( UITableViewCell *) cell forRowAtIndexPath :( NSIndexPath *) indexPath
- {
- UIImage * image = [self getImageForCellAtIndexPath: indexPath]; // obtain an image from the Internet
- [Cell. imageView setImage: image];
- }
This solves the problem of delayed loading, but when the network speed is very slow or the image is very large (assuming, although the figure in the cell is usually small ), you will find that the program may lose the response to the user.
The reason is:
- UIImage * image = [self getImageForCellAtIndexPath: indexPath];
This method may take a lot of time, and the main thread needs to process this method, so the response to the user is lost.
Therefore, we need to propose this method:
- -(Void) updateImageForCellAtIndexPath :( NSIndexPath *) indexPath
- {
- NSAID utoreleasepool * pool = [[NSAID utoreleasepool alloc] init];
- UIImage * image = [self getImageForCellAtIndexPath: indexPath];
- UITableViewCell * cell = [self. tableView cellForRowAtIndexPath: indexPath];
- [Cell. imageView into mselecw.mainthread: @ selector (setImage :) withObject: image waitUntilDone: NO];
- [Pool release];
- }
And then start a new thread to do this.
- -(Void) tableView :( UITableView *) tableView willDisplayCell :( UITableViewCell *) cell forRowAtIndexPath :( NSIndexPath *) indexPath
- {
- [NSThread detachNewThreadSelector: @ selector (updateImageForCellAtIndexPath :) toTarget: self withObject: indexPath];
- }
Similarly, when we need a long period of computing, we also need to open a new thread to do this computing to prevent the program from being suspended.