定义一个全局的float类型的cacheSize,用来记录缓存大小
- (void)_countCatcheSize
{
//获取沙盒路径
NSString *homePath = NSHomeDirectory();
//拼接缓存路径
NSString *imgPath = [homePath stringByAppendingPathComponent:@"Library/Caches/default/com.hackemist.SDWebImageCache.default"];
// NSLog(@"imgPath is %@", imgPath);
//文件管理
NSFileManager *fileManager = [NSFileManager defaultManager];
//取得一个文件夹下所有的文件路径
NSError *error = nil;
NSArray *subPath = [fileManager subpathsOfDirectoryAtPath:imgPath error:&error];
//内存大小
long long sum = 0;
for (NSString *filePath in subPath) {
//取得一个文件的路径
NSString *path = [imgPath stringByAppendingPathComponent:filePath];
//拿到文件的属性
NSDictionary *attributes = [fileManager attributesOfItemAtPath:path error:&error];
NSNumber *fileSize = attributes[NSFileSize];
sum += [fileSize longLongValue];
}
//计算内存
cacheSize = sum / (1024.0 * 1024);
NSLog(@"------%.2f", cacheSize);
}
//单元格出现时记录缓存数据
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
[self _countCatcheSize];
UILabel *label = (UILabel *)[cell viewWithTag:100];
label.text = [NSString stringWithFormat:@"%.1fM", cacheSize];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
//弹出清除对话框
UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"提示" message:@"确定清除缓存?" preferredStyle:UIAlertControllerStyleAlert];
//取消按钮
UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//确定按钮
UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
//确定清空缓存
[[SDImageCache sharedImageCache] clearDisk];
//刷新tableView
[self.tableView reloadData];
}];
[alertCtrl addAction:cancleAction];
[alertCtrl addAction:sureAction];
//弹出对话框
[self presentViewController:alertCtrl animated:YES completion:nil];
}
}