Best way of loading images from application bundle

Aqueel picture Aqueel · Feb 7, 2012 · Viewed 14.8k times · Source

What is the best way of loading images from the application main bundle. I am using

[UIImage imageNamed: "image.png"];

But I have heard that this is not good in terms of memory usage and performance. Can anyone please give his/her feedback on it? My application reads lots of images from main bundle at launch time. I want to make this process as efficient as possible.

Best Regards

Answer

justin picture justin · Feb 7, 2012

If there were one true "Best Way", the means to load images multiple ways would not exist (unless for historical reasons). Therefore, a little understanding will serve you better than distilling an answer down to a "Best Way".

+[UIImage imageNamed:] caches the image for reuse, and it is a sensible default for most purposes. Caching is excellent if used correctly. The cache is good because it can minimize your disk reads and memory usage by sharing and reusing loaded images, rather than reading and allocating a copy for each image you must display. Consider an icon image which you use on multiple screens - would you like that image data to be read and reallocated each time? This may result in redundant reads and allocations of identical image data. If not, use the caching methods.

If you load the image only once and lazily, then you may want consider non-caching approaches.

  • Image data can consume a lot of memory.
  • Reading an image can take a long time -- not just disk i/o, but also converting it into a usable UIImage representation (e.g. decompressing the image).
  • there are also times where you should resize/scale an image. then you'd want a scaled copy.

In short, there are many considerations, but if you have properly scaled assets which you reuse, caching is typically the right choice.

If your assets are not sized properly, then the issue is more fundamental -- you should resize the bundled assets to be appropriate for the purpose if you're experiencing performance problems. Properly sized images also make drawing significantly simpler while retaining the best image quality.