TableViewMediumImageLatency loading is what we will introduce in this article.TableViewDisplay many entries.Image. But one-time slaveServerObtain allImageWaste of traffic on usersServerIt is also a burden, it is best to load as needed, that is, when the user wants to browse this entry, then load it often we will useTableViewMultiple entries are displayed.
Sometimes displayImageHowever, 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 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
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
- UIImage *image = [self getImageForCellAtIndexPath:indexPath];
- UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
- [cell.imageView performSelectorOnMainThread:@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.
The above code is just an example and can be improved more. For example, after going down from the Internet onceImageCache, so you do not need to download it when it is displayed again.
Summary: DetailsTableViewMediumImageThe content of delayed loading has been introduced. I hope this article will help you!