清除缓存功能

字数 251阅读 121

OC 日常笔记碎片知识

前言:几乎每个应用都有清除缓存的功能,因此为了代码复用性,考虑封装功能.

  • 1-实现思路大概分析:

1.先点击didSelectRow,打印文件夹主路径.在里随便生成一个文件,例如”mp3”.
2.先获取文件路径.
3.通过遍历拼接文件.
4.模仿SDWebImage累加文件,计算文件总大小.

  • 2-代码演示(已经封装好的代码,只需给路径,点语法调用就可以计算文件)

给字符串做分类

#import <Foundation/Foundation.h>

@interface NSString (JYhExtenation)
- (unsigned long long)fileSize;
@end
#import "NSString+JYhExtenation.h"

@implementation NSString (JYhExtenation)

- (unsigned long long)fileSize
{
    //初始化总大小
    unsigned long long size = 0;
    //文件管理者
    NSFileManager *mgr = [NSFileManager defaultManager];
    //是否为文件夹
    BOOL isDirectory = NO;
    //路径是否存在
   BOOL exists = [mgr fileExistsAtPath:self isDirectory:&isDirectory];
    if (!exists) return size;
    //如是文件夹isDirectory会返回YES
    if (isDirectory) //文件夹
    {
        //通过遍历获得文件的总大小
        NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self];
        for (NSString *subpatchStr in enumerator)
        {
            //第一步:拼接dirpath文件夹与里面的文件(本质是字符串)
            NSString *fullSubpath = [self stringByAppendingPathComponent:subpatchStr];
            //第二步:获取文件的属性
            size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
        }
    }else // 文件
    {
        size = [mgr attributesOfItemAtPath:self error:nil].fileSize;
    }

    return size;
}
@end
快速计算文件夹尺寸.gif

*会发现有一点偏差. 原因是本身文件夹不是计算范围, 文件夹属于轻量级,只需清除文件夹里的文件即可.

自定义cell把功能封装在里面

  • 3-代码演示:
#import <UIKit/UIKit.h>

@interface JYhClearCacheCell : UITableViewCell

@end
#import "JYhClearCacheCell.h"
//获取caches文件夹
#define JYhCustomPath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"custom"]

--------------------------------------------------------
@implementation JYhClearCacheCell

//初始化样式方法
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        //创建菊花view
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        //开启动画
        [loadingView startAnimating];
        //赋值
        self.accessoryView = loadingView;
        self.textLabel.text = @"清空缓存(努力计算大小...)";

        //在子线程计算缓存大小
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            //获得缓存文件夹路径
//            unsigned long long size = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"custom"].fileSize;
            //计算文件大小
            unsigned long long size = JYhCustomPath.fileSize;
//            JYHLog(@"%@",JYhCustomPath);
            size += [SDImageCache sharedImageCache].getSize;
            
            //转换文件size
            NSString *sizeText = @"0";
            if (size >= 1000 * 1000 * 1000) // size >= 1GB
            {
                sizeText = [NSString stringWithFormat:@"%.1fGB",size / 1000.0 / 1000.0 / 1000.0];
            }else if (size >= 1000 * 1000) // 1GB > size >= 1MB
            {
                sizeText = [NSString stringWithFormat:@"%.1fMB",size / 1000.0 / 1000.0 ];
            }else if (size >= 1000) //1MB > size >= 1KB
            {
                sizeText = [NSString stringWithFormat:@"%zdB",size];
            }
            //生成文字
            NSString *cellStr = [NSString stringWithFormat:@"清除缓存(%@)",sizeText];
            //回到主线程设置文字
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置textLabel
                self.textLabel.text = cellStr;
                //清空控件
                self.accessoryView = nil;
                //设置系统箭头样式
                self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            });
        });
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClear:)];
        [self addGestureRecognizer:tap];
    }
    return self;
}
--------------------------------------------------------
//点击手势方法
- (void)tapClear:(UITapGestureRecognizer *)tap
{  //设置指示器的样式
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    //弹出指示器
    [SVProgressHUD showWithStatus:@"正在清除缓存..."];
   //延迟执行模仿网络繁忙
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        //删除缓存文件
        [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
            //开子线程清除缓存
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                //获取文件管理者
                NSFileManager *mgr = [NSFileManager defaultManager];
                //确定路径
                [mgr removeItemAtPath:JYhCustomPath error:nil];
                //创建一个新的文件夹
                [mgr createDirectoryAtPath:JYhCustomPath withIntermediateDirectories:YES attributes:nil error:nil];
                //所有缓存都清除完毕
                dispatch_async(dispatch_get_main_queue(), ^{
                    //隐藏指示器
                    [SVProgressHUD dismiss];
                    //设置文字
                    self.textLabel.text = @"清除缓存(0B)";
                });
            });
        }];

        
    });
    
    
}

@end

unsigned long long//8个字节,64位的无符号长整形.
unsigned long//4个字节的无符号长整形.
unsigned 变量名 ;是无符号整形.

清除缓存.gif

推荐阅读更多精彩内容