iOS查看和清理缓存

@interface BWMCachesManager : NSObject

/**
* 获取BWMCachesManager单例
*
* @return 返回BWMCachesManager单例对象
*/
+ (BWMCachesManager *)sharedManager;

/**
* 清理缓存
*
* @return 成功返回YES,否则返回NO
*/
- (BOOL)clearCaches;

/**
* 获取所有缓存文件的大小
*
* @return 如23.11 MB
*/
- (NSString *)getAllTheCacheFileSize;

@end

static BWMCachesManager *_cachesManager = nil;

@implementation BWMCachesManager
{
NSString *_cachesDirPath;
}

  • (instancetype)init {
    if (self = [super init]) {
    NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    _cachesDirPath = [cachesPath copy];
    }
    return self;
    }

  • (BWMCachesManager *)sharedManager {
    if (_cachesManager == nil) {
    @synchronized(self) {
    if (_cachesManager == nil) {
    _cachesManager = [[[self class] alloc] init];
    }
    }
    }
    return _cachesManager;
    }

// 清理缓存文件
- (BOOL)clearCaches {
if([self requestCachesFileSize] > 0) {
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:_cachesDirPath];
for (NSString *file in files) {
NSString *path = [_cachesDirPath stringByAppendingPathComponent:file];
if([[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}
}
return YES;
} else {
return NO;
}
}

  • (NSString *)getAllTheCacheFileSize {
    return [NSString stringWithFormat:@”%.2f MB”,[self requestCachesFileSize]];
    }

// 单个文件的大小
- (long long)fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}

// 遍历文件夹获得文件夹大小,返回多少M
- (float)requestCachesFileSize {
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:_cachesDirPath]) return 0;
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:_cachesDirPath] objectEnumerator];
NSString* fileName;
long long folderSize = 0;
while ((fileName = [childFilesEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [_cachesDirPath stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fileAbsolutePath];
}
return folderSize/(1024.0*1024.0);
}

@end

你可能感兴趣的:(iOS查看和清理缓存)