iOS 获取缓存的大小和清除缓存方法

释放双眼,带上耳机,听听看~!

获取缓存的方法:

- (float)filePath {
NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
return [ self folderSizeAtPath:cachPath];
}
//遍历文件夹获得文件夹大小,返回多少M
- (float )folderSizeAtPath:(NSString*) folderPath {
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:folderPath]) return 0;
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
NSString* fileName;
long long folderSize = 0;
while ((fileName = [childFilesEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [folderPath     stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fileAbsolutePath];
}
//SDWebImage框架自身计算缓存的实现
folderSize += [[SDImageCache sharedImageCache] getSize];
return folderSize/(1024.0*1024.0);
}
- (long long) fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if ([manager fileExistsAtPath:filePath]){
return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}

清除缓存的方法:

- (void)clearCacheDidSelected {
WEAK(weakSelf)
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:SF(@"缓存大小为%@,确定要清理缓存吗?",self.cacheStr) preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
weakSelf.cacheStr = @"0.00M";
[weakSelf.sourceArr removeObjectAtIndex:1];
[weakSelf.sourceArr insertObject:weakSelf.cacheStr atIndex:1];
[weakSelf.tableView reloadData];
[weakSelf clearCache];
}];
[alertController addAction:cancelAction];
[alertController addAction:confirmAction];
[self presentViewController:alertController animated:YES completion:nil];
}
- (void)clearCache {
NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
NSFileManager *fileManager=[NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:cachPath]) {
NSArray *childerFiles=[fileManager subpathsAtPath:cachPath];
for (NSString *fileName in childerFiles) {
//如有需要,加入条件,过滤掉不想删除的文件
NSString *absolutePath=[cachPath stringByAppendingPathComponent:fileName];
[fileManager removeItemAtPath:absolutePath error:nil];
}
}
[[SDImageCache sharedImageCache] clearMemory];
}

方法的调用:
//获取缓存的
NSString *cacheStr = [NSString stringWithFormat:@"%.2fM",[self filePath]];
//清除缓存
[self clearCacheDidSelected];

pch

人已赞赏
iOS文章

iOS查看调试手机里的文件

2020-1-1 19:18:22

iOS文章

iOS大小写字符串的转化

2020-1-1 20:20:16

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索