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.