// 创建工具类 ClearnCache 继承NSobject
// .h 文件
#import <Foundation/Foundation.h>
@interface ClearnCache : NSObject
/**
获取文件路劲
@return 返回路径
*/
+ (NSString *)getCachesPath;
/**
计算单个文件的大小
@param filePath 路径
@return 返回结果
*/
+ (long)fileSizeAtpath:(NSString *)filePath;
/**
遍历文件夹获得文件夹大小
*/
+ (float)getCacheSizeAtPath;
/**
清理缓存
*/
+ (void)clearCacheAtPath;
@end
// .m文件
#import "ClearnCache.h"
@implementation ClearnCache
/**
获取路径
*/
+ (NSString *)getCachesPath
{
// 获取caches目录路径
NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
// 拼接路径
NSString *filePath = [cachesPath stringByAppendingPathComponent:@"3D-Project"];
// caches存放缓存,故不需要拼接
return cachesPath;
}
+ (long)fileSizeAtpath:(NSString *)filePath
{
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]) {
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
+ (float)getCacheSizeAtPath
{
NSFileManager *manager = [NSFileManager defaultManager];
// 判断文件路径是否存在
if (![manager fileExistsAtPath:[ClearnCache getCachesPath]]) {
return 0;
}
NSEnumerator *enumerator = [[manager subpathsAtPath:[ClearnCache getCachesPath]]objectEnumerator];
NSString *fileName;
long long folderSize = 0;
while ((fileName = [enumerator nextObject]) != nil) {
NSString* fileAbsolutePath = [[ClearnCache getCachesPath] stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtpath:fileAbsolutePath];
}
return folderSize/(1024.0*1024.0);
}
+ (void)clearCacheAtPath
{
NSFileManager *manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:[ClearnCache getCachesPath]]) {
NSArray *chilederFiles = [manager subpathsAtPath:[ClearnCache getCachesPath]];
for (NSString *fileName in chilederFiles) {
NSString *absolutePath = [[ClearnCache getCachesPath] stringByAppendingPathComponent:fileName];
[manager removeItemAtPath:absolutePath error:nil];
}
}
}
// 使用:
// 计算缓存
CGFloat size =[ClearnCache getCacheSizeAtPath];
NSLog(@"Manage计算缓存:%f",size);
// 清除缓存
[ClearnCache clearCacheAtPath];
计算缓存
-(void)calculateCache{
float cacheSize = 0;
//SDImageCache 单利类,调用 getSize 方法
NSInteger tmpSize = [[SDImageCache sharedImageCache] getSize];
cacheSize = tmpSize / 1024.0 / 1024.0;
_cacheLabel.text = [NSString stringWithFormat:@"%.2fMB",cacheSize];
}
清除缓存
[[SDImageCache sharedImageCache] clearDisk];