//
// MyCache.h
// M
//
// Created by zsl on 2017/11/13.
// Copyright © 2017年zsl. All rights reserved.
//
#import
@interface MyCache : NSObject
+ (CGFloat)getCacheSize;
+ (void)cleanCache;
@end
//
// MyCache.m
// M
//
// Created by zsl on 2017/11/13.
// Copyright © 2017年 zsl. All rights reserved.
//
#import "MyCache.h"
@implementation MyCache
+ (CGFloat) getCacheSize {
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString *cachesDir = [paths lastObject];
NSFileManager * manager = [NSFileManager defaultManager];
CGFloat size = 0;
if ([manager fileExistsAtPath:cachesDir]) {
// 目录下的文件计算大小
NSArray * childrenFile = [manager subpathsAtPath:cachesDir];
for (NSString * fileName in childrenFile) {
NSString * absolutePath = [cachesDir stringByAppendingPathComponent:fileName];
size += [manager attributesOfItemAtPath:absolutePath error:nil].fileSize;
}
//SDWebImage的缓存计算
size += [[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
// 将大小转化为M
return size / 1024.0 / 1024.0;
}else{
return 0;
}
}
//清除缓存
+(void)cleanCache {
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
NSString * cachesDir = [paths lastObject];
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:cachesDir]) {
NSArray *childrenFiles = [fileManager subpathsAtPath:cachesDir];
for (NSString *fileName in childrenFiles) {
// 拼接路径
NSString *absolutePath = [cachesDir stringByAppendingPathComponent:fileName];
// 将文件删除
[fileManager removeItemAtPath:absolutePath error:nil];
}
}
//SDWebImage的清除功能
[[SDImageCache sharedImageCache] clearDisk];
[[SDImageCache sharedImageCache] clearMemory];
}
@end
使用类:
1、获取缓存量
self.cacheLabel.text = [NSString stringWithFormat:@"%.fM",[MyCache getCacheSize]];
2、清理缓存
[MyCache cleanCache];
网友评论