arc4randall
arc4randall

Reputation: 3293

How to stop images from reloading while scrolling in tableview

I have created a UITableView, and have an array of URLs that I need to set their image property for. I have managed to improve the scrolling functionality of the table by using dispatch_async to retrieve the images, and store them in an NSCache that I have declared as a strong property, but now when I scroll through the table, I can see the images from the previous rows in the cells that are appearing, and then when the scrolling stops, the images update to what they should be, but sometimes they will also cycle through a few of the other images along the way. Here is my code within the cellForRowAtIndexPathMethod, does anyone know why this is happening?

UIImage* image = [_imageCache objectForKey:article.imageURL];
if(image){
    [cell.imageRight setImage:image];
} else {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0ul);
dispatch_async(queue, ^{

UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:article.imageURL]]];

dispatch_async(dispatch_get_main_queue(), ^{
    [_imageCache setObject:image forKey:article.imageURL];
    [cell.imageRight setImage:img];
    [cell setNeedsLayout];
    });
});
}

Upvotes: 1

Views: 379

Answers (1)

Abhi Beckert
Abhi Beckert

Reputation: 33349

I would create an NSOperationQueue, and instead of dispatch_async() just add the block to the end of the queue.

Set the maximum concurrent operations to 1, so that only one image will download at a time, which will give better performance over a typical 3G connection.

The first thing each operation should do is check if the image is already in the cache, then abort if so. That way when the same image download is added to the queue 5,000 times, it doesn't matter — because it will only download the first time.

Upvotes: 1

Related Questions