SDWebImage
。但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯、购物、阅读类app的标配功能。
实现的具体步骤
使用注意:过程中需要用到第三方库,请提前安装好: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];}上述两个方法都是在主线程中完成的,如果缓存文件大小非常大的话,计算时间会比较长,会导致应用卡死,考虑到该问题,因此需要将上述代码放到子线程中完成。
//计算完成后,回到主线程继续处理,显示文件大小,除去加载视图,显示箭头,添加点击事件dispatch_async(dispatch_get_main_queue(), ^{ self.detailTextLabel.text = [NSString stringWithFormat:@"%@",sizeText]; self.accessoryView = nil; self.accessoryType = UITableViewCellAccessoryDisclosureIndicator; [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clearCacheClick)]];});4. 清除缓存
SDWebImage
的缓存,二是清除自定义文件缓存- (void)clearCacheClick{ [SVProgressHUD showWithStatus:@"正在清除缓存···"]; [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack]; [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{dispatch_async(dispatch_get_global_queue(0, 0), ^{ NSFileManager *mgr = [NSFileManager defaultManager]; [mgr removeItemAtPath:GYLCustomFile error:nil]; [mgr createDirectoryAtPath:GYLCustomFile withIntermediateDirectories:YES attributes:nil error:nil]; dispatch_async(dispatch_get_main_queue(), ^{[SVProgressHUD dismiss];// 设置文字self.detailTextLabel.text = nil; }); }); }];}注意点:
SDWebImage
清除缓存是在子线程中进行的,清除自定义文件内容应该也放在子线程中(删除大文件可能比较耗时),为了保证两者不冲突,可以将删除自定义文件内容放在SDWebImage
缓存清除完毕之后进行,然后再回到主线程操作。didSelectRowAtIndexPath
方法,那么会导致手势监听不能使用。于是需要在计算时不能点击Cell。userInteractionEnabled=NO
应放在设置文字之后,否则textLabel
将显示为灰色。dealloc
方法来验证,在此情况下,可以使用弱引用的self
来解决。
总结
以上就是关于iOS中清除缓存功能实现的全部内容,希望这篇文章对各位iOS开发者们能有所帮助,如果有疑问大家可以留言交流。