Any way to get a Cached UIImage from my 'Documents' directory?

后端 未结 4 1362
既然无缘
既然无缘 2021-02-04 17:58

I know that the -imageNamed: method returns a Cached UIImage, but the problem is that my image file is stored in \'Documents\', and the -imageNamed: method seems to only search

4条回答
  •  不知归路
    2021-02-04 18:22

    I made an extension of the answer provided by rpetrich and overrode the imageName: method to add more of a drop in replacement. It searches the main bundle first and then looks in the caches directory. You could of course change the caches directory to the document directory.

    @interface UIImage (CacheExtensions)
    + (UIImage *)imageNamed:(NSString *)name;
    + (void)clearCache;
    @end
    
    #import "UIImage+CacheExtensions.h"
    
    static NSMutableDictionary *UIImageCache;
    
    @implementation UIImage (CacheExtensions)
    
    + (UIImage *)imageNamed:(NSString *)name 
    {
        id result;
        if (!UIImageCache)
            UIImageCache = [[NSMutableDictionary alloc] init];
        else {
            result = [UIImageCache objectForKey:name];
            if (result) return result;
        }
    
        // First, check the main bundle for the image
        NSString *imagePath = [[NSBundle mainBundle] pathForResource:name ofType:nil];
    
        result = [UIImage imageWithContentsOfFileimagePath];
        if(result) {
            [UIImageCache setObject:result forKey:name];
            return result;
        }
    
        // If not found, search for the image in the caches directory
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
        NSString *cachesImagePath = [[paths lastObject] stringByAppendingPathComponent:name];
    
        result = [UIImage imageWithContentsOfFile:cachesImagePath];
        if(result) {
            [UIImageCache setObject:result forKey:name];
            return result;
        }
    
        return nil;
    }
    
    + (void)clearCache
    {
        [UIImageCache removeAllObjects];
    }
    
    @end
    

提交回复
热议问题