Lazy Loading UIImages from files without blocking the main thread?

What a decent way to load UIImages on demand without blocking the main thread?

Context: I have several thousand images on the wall that I can scroll through. Obviously, it’s not easy to download all UIImages, so now I just lazily load the ones that are displayed, and then freeing them when they are no longer needed. The problem is that loading UIImages from files takes a little time, long enough to cause stuttering while scrolling. These are far from large images (about 250x250, maybe 20-30 kb each), but they still cause stuttering.

+5
source share
2 answers

I am using my own subclass of UIImageView for something like this. It is mainly used for uploading images (for example, avatars and images on a Twitter stream), so NSURLConnection is used to download an image from a URL. URLConnection then calls the delegate method, which is then used to update the UIImageView. I added an additional later static dictionary with cached images, so the images that are used most often do not need to be loaded every time. This is very useful for things like the twitter avatars mentioned above.

I'm not sure if you are trying to download images from the Internet or locally, so this may not be entirely appropriate for your situation, but I hope this helps ...

0

. UIScrollView. .

//get a dispatch queue
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);


//this will start the image loading in bg
dispatch_async(concurrentQueue, ^{        
    NSData *image = [[NSData alloc] initWithContentsOfURL:imageURL];

    //this will set the image when loading is finished
    dispatch_async(dispatch_get_main_queue(), ^{
        imageView.image = [UIImage imageWithData:image];
    });
});  
0

All Articles