Tuesday, July 9, 2013

imageNamed v/s imageWithContentsOfFile methods in Objective C

While loading image from your xcode resource bundle usually we use imageNamed and imageWithContentsOfFile methods,

imageNamed works on basis of cache mechanism, this method looks in to system cache for an image object with the specified name and returns that object if it exists.If the image object is not in the cache then it loads image from a specified file from resource bundle and caches it, then returns the resulting object.
ex:- UIImage *image = [UIImage imageNamed:@"viewBg"];

imageWithContentsOfFile simply loads the image from resource bundle with no caching.
ex:- UIImage *image = [UIImage imageWithContentsOfFile:@"viewBg"];

Pros & Cons: 
imageNamed method is better to use when images are going to be reused in your app, say for example Custom NavigationBar image in your app, View background etc.

imageWithContentsOfFile method is better to use when you are not reusing a particular image frequently in your app, so that this particular image won't go in to system cache & simply won't occupy space in system cache unnecessarily.

For more information about UIImage here is a link for Apple's Documentation

Hope this post was helpful, any comments or suggestions is acceptable.


  1. Hi Arun
    Where can I find a code example for image loading. I am trying to use imageWithContentsOfFile but still doesn't work. Loading the image with imageNamed I get a full screen image. Using the other method, the image was reduced in size.

  2. @Cau may I know what exactly you are trying to do? If you can brief your requirement and problem I can help you out.
    Basically you need to set proper "frame" for your UIImageView object and in addition to this you can even cross check your UIImageView "contentMode" and "autoresizingMask" properties for the image rendering & alignment.