iOS的缓存一般分为两部分,一部分是下载数据产生的缓存,这部分有系统做了缓存,在沙盒里面,还有一部分是图片的缓存,一般来说这部分的缓存较大,如果是用户自己保存,那就要根据保存路径自己找到,然后删除,不过大部分应该是用的sdwebimage进行的缓存,直接使用sdwebimage的方法就可以了,直接上代码
获取缓存大小:
-(void)getCacheSize{
//得到缓存路径
NSString * path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSFileManager * manager = [NSFileManager defaultManager];
CGFloat size = 0;
//首先判断是否存在缓存文件
if ([manager fileExistsAtPath:path]) {
NSArray * childFile = [manager subpathsAtPath:path];
for (NSString * fileName in childFile) {
//缓存文件绝对路径
NSString * absolutPath = [path stringByAppendingPathComponent:fileName];
size = size + [manager attributesOfItemAtPath:absolutPath error:nil].fileSize;
}
//计算sdwebimage的缓存和系统缓存总和
size = size + [[SDWebImageManager sharedManager].imageCache getSize];
}
size = [NSString stringWithFormat:@"%.2fM",size / 1024 / 1024];
}
删除缓存:
-(void)cleanCache{
//获取缓存路径
NSString * path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSFileManager * manager = [NSFileManager defaultManager];
//判断是否存在缓存文件
if ([manager fileExistsAtPath:path]) {
NSArray * childFile = [manager subpathsAtPath:path];
//逐个删除缓存文件
for (NSString *fileName in childFile) {
NSString * absolutPat = [path stringByAppendingPathComponent:fileName];
[manager removeItemAtPath:absolutPat error:nil];
}
//删除sdwebimage的缓存
[[SDWebImageManager sharedManager].imageCache clearMemory];
}
//这里是又调用了得到缓存文件大小的方法,是因为不确定是否删除了所有的缓存,所以要计算一遍,展示出来
[self getCacheSize];
}