简述:下面的是根据SDImage图片缓存与文件缓存结合在一起来写的
需要导入SDImage三方,一般需要导入头文件
#import "UIImageView+WebCache.h"
效果图:
1.设置一个按钮来调用清除缓存
//清缓存提示框 NSString *message = [NSString stringWithFormat:@"可清除大小%.2fM",[self folderSizeAtPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]]]; UIAlertController * al = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { [self clearCache:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]]; }]; [al addAction:okAction]; UIAlertAction *okAction2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { }]; [al addAction:okAction2]; [self presentViewController:al animated:YES completion:^{ }];
2.调用方法
#pragma mark--计算缓存的大小 /** * 所有的缓存调用的计算大小 */ -(float)folderSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; float folderSize; if ([fileManager fileExistsAtPath:path]) { NSArray *childerFiles=[fileManager subpathsAtPath:path]; for (NSString *fileName in childerFiles) { NSString *absolutePath=[path stringByAppendingPathComponent:fileName]; folderSize +=[self fileSizeAtPath:absolutePath]; } //SDWebImage框架自身计算缓存的实现 folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0; return folderSize; } return 0; } /** * 和上面的是连贯在一起的 */ -(float)fileSizeAtPath:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; if([fileManager fileExistsAtPath:path]){ long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize; return size/1024.0/1024.0; } return 0; } #pragma mark--清除缓存 -(void)clearCache:(NSString *)path{ NSFileManager *fileManager=[NSFileManager defaultManager]; if ([fileManager fileExistsAtPath:path]) { NSArray *childerFiles=[fileManager subpathsAtPath:path]; for (NSString *fileName in childerFiles) { //如有需要,加入条件,过滤掉不想删除的文件 NSString *absolutePath=[path stringByAppendingPathComponent:fileName]; [fileManager removeItemAtPath:absolutePath error:nil]; } } [[SDImageCache sharedImageCache] cleanDisk]; }
清理缓存demo 密码: zjbr
封装过的缓存demo 密码: qx5q