Lazy Loading UIImages from files without blocking main thread?
What's a decent way to load UIImages on demand without blocking the main thread?
Context: I have a couple thousand images on a wall that I can scroll through. Obviously it's not feasible to just load all the UIImages, so right now I'm just lazy loading the ones that are getting displayed, and then releasing them when they're no longer needed. The problem is that loading UIImages from files takes a noticeable bit of time, just long enough to cause stuttering while scrolling. These are by no means large images (around 250x250, maybe 20-3开发者_Python百科0kb each), but they still cause stuttering.
I use a custom UIImageView subclass for something similar to this. It's mostly used to download images (think avatars and images in a twitter stream for example), so it uses an NSURLConnection to download the image from an URL. The URLConnection then calls a delegate method when done, which I then use to update the UIImageView. An extra I added later is a static dictionary with cached images, so images that are used more often don't have to be downloaded every time. This is pretty useful for stuff like the twitter avatars mentioned earlier.
I'm not sure if you're trying to load the images from web or locally, so this might not apply perfectly to your situation, but I hope this helps...
You can do this very simply way. First create a queue when create a UIScrollView object. After you create you can load image from your local storage with queue just created.
//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];
});
});
精彩评论