Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImage setImage is very, very slow

I'm trying to load an image from a local URL using the following:

UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:fileURL]];
[self.imageView setImage:image];
NSLog(@"imageView set");

So I see in the console "imageView set" almost immediately, but it takes a very long time for it to be reflected in the UI (sometimes a few minutes!).

Any idea why this is happening?

like image 223
Andy Hin Avatar asked May 20 '13 04:05

Andy Hin


2 Answers

This happened to me when I was setting the image in a background thread (in which I was downloading the image file). Just make sure your code is run in the main thread. The image will change immediately.

// In a background thread...

UIImage *image = ... // Build or download the image

dispatch_async(dispatch_get_main_queue(), ^{ 
    [self.imageView setImage:image]; // Run in main thread (UI thread)
});
like image 137
Ballenato Avatar answered Oct 21 '22 09:10

Ballenato


You should load up instruments and see what exactly it is doing.

For starters, you should do what you can to avoid I/O on the drawing thread. Also, are there other I/O requests at the same time?

A UIImage does not necessarily need to be a singular bitmap representation -- it may be backed by a cache and/or loaded lazily. So just because an 'image' is 'set', does not mean that the optimal bitmap has been loaded into memory and prepared for rendering -- it may be deferred until render (draw) is requested.

Profiling OTOH will tell you (generally) why it is taking longer than expected.

like image 24
justin Avatar answered Oct 21 '22 11:10

justin