您的位置:首页 > 移动开发 > IOS开发

iOS缓存文件大小显示功能和一键清理功能的实现方法

2016-10-20 10:59 966 查看

缓存占用了系统的大量空间,如何实时动态的显示缓存的大小,使用户清晰的了解缓存的积累情况,有效的进行一键清理呢?
为方便读者和未来自己更好理解,我们创建这样场景。(在表视图的清除缓存一单元格内创建一个UILabel *cacheLabel用于显示当前缓存,当点击单元格弹出提示框,点击确定,清除缓存)。

  下面是实现代码:

#pragma mark - 计算缓存大小
- (NSString *)getCacheSize
{
//定义变量存储总的缓存大小
long long sumSize = 0;
//01.获取当前图片缓存路径
NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
//02.创建文件管理对象
NSFileManager *filemanager = [NSFileManager defaultManager];
//获取当前缓存路径下的所有子路径
NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:cacheFilePath error:nil];
//遍历所有子文件
for (NSString *subPath in subPaths) {
//1).拼接完整路径
NSString *filePath = [cacheFilePath stringByAppendingFormat:@"/%@",subPath];
//2).计算文件的大小
long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];
//3).加载到文件的大小
sumSize += fileSize;
}
float size_m = sumSize/(1000*1000);
return [NSString stringWithFormat:@"%.2fM",size_m];
}
#pragma mark - 清除缓存提示(UITableViewDataSourceDelegate)
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"缓存清除" message:@"确定清除缓存?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
[alertView show];
}
}
#pragma mark - UIAlertViewDelegate方法实现
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSLog(@"代码执行到此");
//判断点击的是确认键
if (buttonIndex == 1) {
//01......
NSFileManager *fileManager = [NSFileManager defaultManager];
//02.....
NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
//03......
[fileManager removeItemAtPath:cacheFilePath error:nil];
//04刷新第一行单元格
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
[_tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//05 :04和05使用其一即可
[_tableView reloadData];//刷新表视图
}
@pragma -mark -放置于.m文件首段较为合适,本DEMO仅做功能性展示,实时监测缓存大小,从其他界面跳转到本页面,也需要刷新下表视图
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:YES];
[_tableView reloadData];
}

以上所述是小编给大家介绍的iOS缓存文件大小显示功能和一键清理功能的实现方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios 缓存 清理