要清除缓存之前,我们需要知道缓存现在已经是多大了,是否需要我们的清理。
unsigned long long size = XMGCustomCacheFile.fileSize;
size += [SDImageCache sharedImageCache].getSize;
展示缓存的大小:
NSString *sizeText = nil;
if (size >= pow(10, 9)) { // size >= 1GB
sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
} else if (size >= pow(10, 6)) { // 1GB > size >= 1MB
sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
} else if (size >= pow(10, 3)) { // 1MB > size >= 1KB
sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
} else { // 1KB > size
sizeText = [NSString stringWithFormat:@"%zdB", size];
}
现在我们正式清除缓存!
弹出指示器:
[SVProgressHUD showWithStatus:@"正在清除缓存..." maskType:SVProgressHUDMaskTypeBlack];
删除SDWebImage的缓存:
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{}];
在删除SDWebImage缓存的Block代码块里,开辟子线程,清除自定义的缓存:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr removeItemAtPath:XMGCustomCacheFile error:nil];
[mgr createDirectoryAtPath:XMGCustomCacheFile withIntermediateDirectories:YES attributes:nil error:nil];
});
});
/**
* 清除缓存
*/
- (void)clearCache
{
// 弹出指示器
[SVProgressHUD showWithStatus:@"正在清除缓存..." maskType:SVProgressHUDMaskTypeBlack];
// 删除SDWebImage的缓存
[[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
// 删除自定义的缓存
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr removeItemAtPath:SUNCustomCacheFile error:nil];
[mgr createDirectoryAtPath:SUNCustomCacheFile withIntermediateDirectories:YES attributes:nil error:nil];
// 所有的缓存都清除完毕
dispatch_async(dispatch_get_main_queue(), ^{
// 隐藏指示器
[SVProgressHUD dismiss];
// 设置文字
self.textLabel.text = @"清除缓存(0B)";
});
});
}];
}