iOS中设置清除缓存功能的实现方法

2020-01-21 00:05:34于海丽

绝大多数应用中都存在着清楚缓存的功能,形形色色,各有千秋,现为大家介绍一种最基础的清除缓存的方法。清除缓存基本上都是在设置界面的某一个Cell,于是我们可以把清除缓存封装在某一个自定义Cell中,如下图所示:

ios,清除缓存功能

具体步骤

使用注意:过程中需要用到第三方库,请提前安装好:SDWebImage、SVProgressHUD。

1. 创建自定义Cell,命名为GYLClearCacheCell

重写initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier方法,设置基本内容,如文字等等;主要代码如下:


- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
 {
  if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    // 设置加载视图
    UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [loadingView startAnimating];
    self.accessoryView = loadingView;
    //设置文字
    self.textLabel.text = @"清楚缓存";
    self.detailTextLabel.text = @"正在计算"; 
 }
  return self;
}

2. 计算缓存文件大小

缓存文件包括两部分,一部分是使用SDWebImage缓存的内容,其次可能存在自定义的文件夹中的内容(视频,音频等内容),于是计算要分两部分,主要代码如下:


unsigned long long size =
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"CustomFile"].fileSize;
//fileSize是封装在Category中的。
size += [SDImageCache sharedImageCache].getSize;  //CustomFile + SDWebImage 缓存
//设置文件大小格式
NSString sizeText = nil;
if (size >= pow(10, 9)) {
 sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
}else if (size >= pow(10, 6)) {
 sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
}else if (size >= pow(10, 3)) {
 sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
}else {
 sizeText = [NSString stringWithFormat:@"%zdB", size];
}

上述两个方法都是在主线程中完成的,如果缓存文件大小非常大的话,计算时间会比较长,会导致应用卡死,考虑到该问题,因此需要将上述代码放到子线程中完成。