iOS中既可以计算沙盒路径下缓存空间的大小,也可以手动清除缓存。其中大部分app会用到SDWebImage,同样需要清除。
1.获取缓存的沙盒路径
这里 NSString *path = [NSString stringWithFormat:@"%@/Library/Caches",NSHomeDirectory()];
2.获取缓存大小
CGFloat fileSize = [self folderSizeAtPath:path];
-(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];
}
folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;//再加上SDWebImage的缓存大小
return folderSize;
}
return 0;
}
3.消除缓存
[self clearCache:path];
-(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];//清除SDImageCache的缓存内容
}