IOS developmentHow to solveTableViewMediumImageDelayed loading is the content to be introduced in this article, mainly to learnTableViewLoadImage. For details, refer to the details in this article.
We often use tableView to display many entries. Sometimes we need to display images. However, 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.
Therefore, 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, the image will be cached once it is down from the Internet and will not be downloaded when it is displayed again.
Summary:IOS developmentHow to solveTableViewMediumImageThe content of delayed loading has been introduced. I hope this article will help you!