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 ?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.