清除缓存的两种实现方式
计算缓存的大小,然后清除缓存分两种:1>图片缓存;2>cache文件夹中的缓存。
1>对于清除图片缓存:SDWebImage就可以做到。
// 计算文件大小
NSUInteger imageSize = [SDImageCachesharedImageCache].getSize;
// 进行单位转换:将byte转成M
double byteSize = imageSize / 1000.0 / 1000.0;
// 清除缓存
// 清除过期缓存
// [[SDImageCache sharedImageCache] cleanDisk];
// 清除所有图片缓存
[[SDImageCachesharedImageCache] clearDisk];
2>cache文件夹中的缓存:使用文件管理者计算缓存大小,然后清除缓存的文件夹实现的思路是:文件夹没有大小属性,只有文件有大小属性。遍历每一个文件夹中的文件,将每一个文件的大小加起来,得到的就是cache文件夹的大小。
//文件管理者
NSFileManager *mgr = [NSFileManagerdefaultManager];
// 缓存的路径
NSString *caches =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES)lastObject];
// 获取所有的子路径
NSArray *subpaths = [mgr subpathsAtPath:caches];
// 文件的总的字节数
NSInteger totalByteSize = 0;
for (NSString *subpathin subpaths) {
// 子路径的全路径
NSString *fullSubpath = [caches stringByAppendingPathComponent:subpath];
// 判断是不是文件
BOOL dir = NO;
[mgr fileExistsAtPath:fullSubpath isDirectory:&dir];
if (dir == NO) { // 文件
totalByteSize += [[mgr attributesOfItemAtPath:fullSubpatherror:nil][NSFileSize]integerValue];
}
}
// 删除caches文件夹中的所有内容
[mgr removeItemAtPath:cacheserror:nil];