Does the UIImage Cache image? Does the UIImage Cache image? ios ios

Does the UIImage Cache image?


  • The -initWithContentsOfFile: creates a new image without caching, it's an ordinary initialization method.

  • The +imageNamed: method uses cache. Here's a documentation from UIImage Reference:

    This method looks in the system caches for an image object with the specified name and returns that object if it exists. If a matching image object is not already in the cache, this method loads the image data from the specified file, caches it, and then returns the resulting object.

    UIImage will retain loaded image, keeping it alive until low memory condition will cause the cache to be purged.

Update for Swift:In Swift the UIImage(named: "...") function is the one that caches the image.


Just wanted to leave this here to help deal with the pathnames issue. This is a method that you can put on a UIImage category.

+(UIImage *)imageNamed:(NSString *)name cache:(BOOL)cache {    if (cache)        return [UIImage imageNamed:name];    name = [[NSBundle mainBundle] pathForResource:[name stringByDeletingPathExtension] ofType:[name pathExtension]];     UIImage *retVal = [[UIImage  alloc] initWithContentsOfFile:name];    return retVal;}

If you don't have an easy way to switch to cached, you might end up just using `imageNamed. This is a big mistake in most cases. See this great answer for more details (and upvote both question and answer!).


@Dan Rosenstark answer in swift..

extension UIImage {    static func imageNamed(name: String, cache: Bool) -> UIImage? {        if (cache) {            return UIImage(named: name)        }        // Using NSString for stringByDeletingPathExtension        let fullName = NSString(string: name)        let fileName = fullName.stringByDeletingPathExtension        let ext = fullName.pathExtension        let resourcePath = NSBundle.mainBundle().pathForResource(fileName, ofType: ext)        if let path = resourcePath {            return UIImage(contentsOfFile: path)        }        return nil    }}