When should someone use UIImage's method init(contentsOfFile:), when is appropriate to use init(named:) and when init(data:)? I read about it and it seems the only difference is that with init(named:) image stays around for a while and with init(contentsOfFile:) is it deallocated as soon as possible eg when it is not on screen anymore. Please correct my assumptions if they are wrong. Not sure what init(data:) is good for.
1 Answer
you use init(contentsOfFile:) when you for example have a path to an image stored somewhere on your phone.
you use init(named:) when you have an image with the passed name in your application bundle.
and you use init(data:) when you have some image data (for example you downloaded the image data from some web source) and want to create the image from that data.
one important difference between the three initializers is that only the imageNamed initializer caches the returned image object!
you should really consult the official documentation for questions like this though: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/#//apple_ref/doc/uid/TP40006890-CH3-SW11
4 Comments
initWithContentsOfFile does not cache the image object. imageNamed does.If you have an image file that will only be displayed once and wish to ensure that it does not get added to the system’s cache, you should instead create your image using imageWithContentsOfFile:. This will keep your single-use image out of the system image cache, potentially improving the memory use characteristics of your app.