您的位置:首页 > 其它

清除缓存---更多页面的实现

2015-09-01 19:47 337 查看

思路:用静态单元格构建UI,然后取到缓存数据,第三方资源清除缓存







静态单元格------用的比较少:
特点:单元格不复用,只能在TabaleViewController里边用
优点:不需要实现协议方法

在storyBoard中构建UI,把控制器的content选项改为static静态的,采用分组的样式,往上边添加UI控件,搭建好外观;

清除缓存

1、计算缓存大小:
缓存:每一个App都有一个对应的沙盒,存放从网络上缓存的图片,清除缓存首先要拿到沙盒里的数据大小;
思路:

//1、找到沙盒路径
//2、拼接出来缓存路径
//3、文件管家(单例对象)
//4、用文件管家取出所有子文件的路径
//5、遍历路径:拼接路径--》拿到文件属性--》取到文件大小---》累加起来
实现:

- (void)_countCacheSize
{
//找到沙盒路径
NSString *homePath = NSHomeDirectory();

//拼接出来缓存路径
NSString *imgsPath = [homePath stringByAppendingPathComponent:@"Library/caches/default/com.hackemist.SDWebImageCache.default"];

//文件管家(单例对象)
NSFileManager *manager = [NSFileManager defaultManager];

//用文件管家取出所有子文件的路径
NSError *error = nil;
NSArray *arr = [manager subpathsOfDirectoryAtPath:imgsPath error:&error];

long long sum = 0;
//遍历路径:拼接路径--》拿到文件属性
--》取到文件大小---》累加起来
for (NSString *path in arr) {
//拼接路径
NSString *filePath = [imgsPath stringByAppendingPathComponent:path];
//拿到文件属性
NSDictionary *dic = [manager attributesOfItemAtPath:filePath error:&error];
//取到文件大小
NSNumber *fileSize = dic[NSFileSize];

sum += [fileSize longLongValue];
}

cacheSize = sum / (1024.0 * 1024);
}

2、显示当前缓存大小
只有第一行单元格里有缓存label,因此在单元格将出现的方法中,我们判断第一行单元格,取到label,并且赋值显示

//单元格将要显示时
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath == 0) {
[self _countCacheSize];
UILabel *label = (UILabel *)[cell viewWithTag:100];
label.text = [NSString stringWithFormat:@"%.1fM", cacheSize];
}
}
3、清除缓存
当点击第一个单元格时,弹出一个alert视图,询问是否清除,点击确定后,通过第三方资源SDWebImage中的
[[SDImageCachesharedImageCache]clearDisk];实现缓存的清除

实现:

//单元格的触发方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row == 0) {
//弹出清除确认框
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"警告" message:@"确定清除"
preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:cancelAction];

UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction
*action) {
//确定清除缓存
[[SDImageCache sharedImageCache] clearDisk];

//刷新tableView
[self.tableView reloadData];
}];

[alert addAction:sureAcrion];
[self presentViewController:alert animated:YES completion:nil];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: