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

后端 未结 4 1364
既然无缘
既然无缘 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:43

    The simplest way would be an NSMutableDictionary storing the cached images and a clear cache method:

    @interface UIImage (CacheExtensions)
    + (id)cachedImageWithContentsOfFile:(NSString *)path;
    + (void)clearCache;
    @end
    
    static NSMutableDictionary *UIImageCache;
    
    @implementation UIImage (CacheExtensions)
    + (id)cachedImageWithContentsOfFile:(NSString *)path
    {
        id result;
        if (!UIImageCache)
            UIImageCache = [[NSMutableDictionary alloc] init];
        else {
            result = [UIImageCache objectForKey:path];
            if (result)
                return result;
        }
        result = [UIImage imageWithContentsOfFile:path];
        [UIImageCache setObject:result forKey:path];
        return result;
    }
    + (void)clearCache
    {
        [UIImageCache removeAllObjects];
    }
    @end
    

    Note: you should call +[UIImage clearCache] from your didReceiveMemoryWarning method. Also, clearCache will invalidate all objects in the cache, not just unused items; a UIImage subclass and more complicated caching mechanism would be required to remedy this.

提交回复
热议问题