SDWebImage图片缓存清理以及缓存大小计算

SDWebImage缓存的相关操作主要通过SDImageCache这个类实现

// SDImageCache是一个单例
SDImageCache * cache = [SDImageCache sharedImageCache];
  • 缓存清理
/**
 * Async clear all disk cached images. Non-blocking method - returns immediately.
 * @param completion    A block that should be executed after cache expiration completes (optional)
 */
- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion;
// 具体实现
- (void)clearDiskOnCompletion:(nullable SDWebImageNoParamsBlock)completion {
    dispatch_async(self.ioQueue, ^{
        [_fileManager removeItemAtPath:self.diskCachePath error:nil];
        [_fileManager createDirectoryAtPath:self.diskCachePath
                withIntermediateDirectories:YES
                                 attributes:nil
                                      error:NULL];

        if (completion) {
            dispatch_async(dispatch_get_main_queue(), ^{
                completion();
            });
        }
    });
}
  • 缓存大小
/**
 * Get the size used by the disk cache
 */
- (NSUInteger)getSize;
// 注意:返回值单位为字节
// 具体实现
- (NSUInteger)getSize {
    __block NSUInteger size = 0;
    dispatch_sync(self.ioQueue, ^{
        NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
        for (NSString *fileName in fileEnumerator) {
            NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
            NSDictionary *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
            size += [attrs fileSize];
        }
    });
    return size;
}

app中清除缓存实现

- (void)clearTmpPics
{
    NSUInteger tmpSize = [[SDImageCache sharedImageCache] getSize];
    
    NSString *clearCacheName;
    if (tmpSize >= 1024*1024*1024) {
        clearCacheName = [NSString stringWithFormat:@"清理缓存(%0.2fG)",tmpSize /(1024.f*1024.f*1024.f)];
    }else if (tmpSize >= 1024*1024) {
        clearCacheName = [NSString stringWithFormat:@"清理缓存(%0.2fM)",tmpSize /(1024.f*1024.f)];
    }else{
        clearCacheName = [NSString stringWithFormat:@"清理缓存(%0.2fK)",tmpSize / 1024.f];
    }

    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        [Tools showHUD:clearCacheName];
    }];

}

其他操作参见SDImageCache

版权声明:出自MajorLMJ技术博客的原创作品 ,转载时必须注明出处及相应链接!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容