- 只需要清理SDWebImage的图片缓存,直接用SDImageCache单例的getSize方法
// 字节大小
NSInteger byteSize = [SDImageCache sharedImageCache].getSize;
// M大小 苹果电脑计算不是1024
double size = byteSize / 1000.0 / 1000.0;
NSString *cacheSize = [NSString stringWithFormat:@"缓存大小(%.1fM)", size];
/**
* 计算当前文件\文件夹的内容大小
*/
- (void)clearCache
{
// 提醒
UIActivityIndicatorView *circle = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[circle startAnimating];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:circle];
// 清除缓存
[[SDImageCache sharedImageCache] clearDisk];
// 显示按钮
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"清除缓存" style:0 target:self action:@selector(clearCache)];
self.navigationItem.title = [NSString stringWithFormat:@"缓存大小(0M)"];
}
2.除了图片还有其他缓存文件就需要删除Library/Cache文件夹,搞一个NSString分类,给一个获取文件夹、文件的所有大小的方法
- (NSInteger)fileSize
{
NSFileManager *mgr = [NSFileManager defaultManager];
// 判断是否为文件
BOOL dir = NO;
BOOL exists = [mgr fileExistsAtPath:self isDirectory:&dir];
// 文件\文件夹不存在
if (exists == NO) return 0;
if (dir) { // self是一个文件夹
// 遍历caches里面的所有内容 --- 直接和间接内容
NSArray *subpaths = [mgr subpathsAtPath:self];
NSInteger totalByteSize = 0;
for (NSString *subpath in subpaths) {
// 获得全路径
NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
// 判断是否为文件
BOOL dir = NO;
[mgr fileExistsAtPath:fullSubpath isDirectory:&dir];
if (dir == NO) { // 文件
totalByteSize += [[mgr attributesOfItemAtPath:fullSubpath error:nil][NSFileSize] integerValue];
}
}
return totalByteSize;
} else { // self是一个文件
return [[mgr attributesOfItemAtPath:self error:nil][NSFileSize] integerValue];
}
}
使用分类计算大小,直接删除cache文件夹
- (void)fileOperation
{
// 文件管理者
NSFileManager *mgr = [NSFileManager defaultManager];
// 缓存路径
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//文件大小
NSInteger cacheSize = [caches fileSize];
NSLog(@"%zd",cacheSize);
// 删除文件夹
[mgr removeItemAtPath:caches error:nil];
}
网友评论