0
votes

I have an UIImage in the Documents directory. I would like to load it and cache it in the memory.

To create and cache a UIImage, we should use + (UIImage *)imageNamed:(NSString *)name method, but the problem with this methods is that the image should be in the application bundle. When i use the other methods, initWithContentsOfFile, ... the image is not cached.

How to load an UIImage from the documents directory and cache it ?

1
You need to create your own caching mechanism for images loaded with anything other than imageNamed:.rmaddy
do you have an idea how to create a caching mechanism ?samir
NSDictionary will work. You just need a way to clear the cache when memory gets low.rmaddy
ohh, i am very stupid.Clear for me, thanks for your answer.samir

1 Answers

1
votes

You could add an NSCache to your AppDelegate, and have a method like:

- (UIImage *)cachedImageWithFilePath:(NSString *)path {
    // first check for a hit in the cache
    UIImage *cachedImage = [_imageCache objectForKey:path];
    if (cachedImage)
      return cachedImage;

    // load the image from disk and add to the cache
    UIImage *newImage = [[UIImage alloc] initWithContentsOfFile:path];
    [_imageCache setObject:newImage forKey:path];
    return newImage;
}

Edit:

Article on NSCache, Apple Documentation