• iOS-App缓存数据计算与清除


    思路: 

    ①计算缓存数据,计算整个应用程序缓存数据 

    ② 沙盒(Cache)缓存(SDWebImage:帮我们做了缓存)

    ③ 获取cache文件夹尺寸

    // 获取Caches文件夹路径

    //NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

    在沙盒路径下追加路径

    封装文件管理类,获取文件夹尺寸

    HKFileTool

    NS_ASSUME_NONNULL_BEGIN
    /*
     业务类:以后开发中用来专门处理某件事情,网络处理,缓存处理
     */
    #define HKFileCachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
    @interface HKFileTool : NSObject
    /**
     *  获取文件夹尺寸
     *
     *  @param directoryPath 文件夹路径
     *
     */
    + (void)getFileSize:(NSString *)directoryPath completion:(void(^)(NSInteger))completion;
    
    
    /**
     *  删除文件夹所有文件
     *
     *  @param directoryPath 文件夹路径
     */
    + (void)removeDirectoryPath:(NSString *)directoryPath;
    
    @end
    
    NS_ASSUME_NONNULL_END
    + (void)removeDirectoryPath:(NSString *)directoryPath
    {
        // 获取文件管理者
        NSFileManager *mgr = [NSFileManager defaultManager];
        
        BOOL isDirectory;
        BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory];
        
        if (!isExist || !isDirectory) {
            // 抛异常
            // name:异常名称
            // reason:报错原因
            NSException *excp = [NSException exceptionWithName:@"pathError" reason:@"笨蛋 需要传入的是文件夹路径,并且路径要存在" userInfo:nil];
            [excp raise];
        }
        // 获取cache文件夹下所有文件,不包括子路径的子路径
        NSArray *subPaths = [mgr contentsOfDirectoryAtPath:directoryPath error:nil];
        
        for (NSString *subPath in subPaths) {
            // 拼接完成全路径
            NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath];
            
            // 删除路径
            [mgr removeItemAtPath:filePath error:nil];
        }
        
    }
    
    // 自己去计算SDWebImage做的缓存
    + (void)getFileSize:(NSString *)directoryPath completion:(void(^)(NSInteger))completion
    {
    
        // 获取文件管理者
        NSFileManager *mgr = [NSFileManager defaultManager];
        BOOL isDirectory;
        BOOL isExist = [mgr fileExistsAtPath:directoryPath isDirectory:&isDirectory];
        
        if (!isExist || !isDirectory) {
            // 抛异常
            // name:异常名称
            // reason:报错原因
            NSException *excp = [NSException exceptionWithName:@"pathError" reason:@"笨蛋 需要传入的是文件夹路径,并且路径要存在" userInfo:nil];
            [excp raise];
        }
        //异步获取文件夹路径
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 获取文件夹下所有的子路径,包含子路径的子路径
            NSArray *subPaths = [mgr subpathsAtPath:directoryPath];
            
            NSInteger totalSize = 0;
            
            for (NSString *subPath in subPaths) {
                // 获取文件全路径
                NSString *filePath = [directoryPath stringByAppendingPathComponent:subPath];
                
                // 判断隐藏文件
                if ([filePath containsString:@".DS"]) continue;
                
                // 判断是否文件夹
                BOOL isDirectory;
                // 判断文件是否存在,并且判断是否是文件夹
                BOOL isExist = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory];
                if (!isExist || isDirectory) continue;
                
                // 获取文件属性
                // attributesOfItemAtPath:只能获取文件尺寸,获取文件夹不对,
                NSDictionary *attr = [mgr attributesOfItemAtPath:filePath error:nil];
                
                // 获取文件尺寸
                NSInteger fileSize = [attr fileSize];
                
                totalSize += fileSize;
            }
            
            // 计算完成回调
            dispatch_sync(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(totalSize);
                }
            });
        });
    }
    
    //单个图片缓存计算
    - (void)getFileSize
    {
        // NSFileManager
        // attributesOfItemAtPath:指定文件路径,就能获取文件属性
        // 把所有文件尺寸加起来
        // 获取Caches文件夹路径
        NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
        // 获取default文件路径
        NSString *defaultPath = [cachePath stringByAppendingPathComponent:@"default/com.hackemist.SDWebImageCache.default/1b2ddf3a6025383675a08262439c1478.jpg"];
        // 遍历文件夹所有文件,一个一个加起来
        // 获取文件管理者
        NSFileManager *mgr = [NSFileManager defaultManager];
        // 获取文件属性
        // attributesOfItemAtPath:只能获取文件尺寸,获取文件夹不对,
        NSDictionary *attr = [mgr attributesOfItemAtPath:defaultPath error:nil];
        // default尺寸
        NSInteger fileSize = [attr fileSize];
        NSLog(@"%ld",fileSize);
    
    }
    @end

     

    使用:

    1.获取文件夹尺寸

    @interface HKSettingViewController ()
    @property (nonatomic, assign) NSInteger totalSize;
    @end
    
    [SVProgressHUD showWithStatus:@"正在计算缓存尺寸...."];
    // 获取文件夹尺寸
    // 文件夹非常小,如果我的文件非常大
    HKWeakSelf
    [HKFileTool getFileSize:HKFileCachePath completion:^(NSInteger totalSize) {
      HKStrongSelf
      self.totalSize = totalSize;
      [self.tableView reloadData];
      [SVProgressHUD dismiss];
    }];

    2.获取缓存字符串

    // 获取缓存尺寸字符串
    cell.textLabel.text = [self sizeStr];
    // 获取缓存尺寸字符串
    - (NSString *)sizeStr
    {
        NSInteger totalSize = _totalSize;
        NSString *sizeStr = @"清除缓存";
        // MB KB B
        if (totalSize > 1000 * 1000) {
            // MB
            CGFloat sizeF = totalSize / 1000.0 / 1000.0;
            sizeStr = [NSString stringWithFormat:@"%@(%.1fMB)",sizeStr,sizeF];
        } else if (totalSize > 1000) {
            // KB
            CGFloat sizeF = totalSize / 1000.0;
            sizeStr = [NSString stringWithFormat:@"%@(%.1fKB)",sizeStr,sizeF];
        } else if (totalSize > 0) {
            // B
            sizeStr = [NSString stringWithFormat:@"%@(%.ldB)",sizeStr,totalSize];
        }
        
        return sizeStr;
    }

    3.清除缓存

    // 点击cell就会调用
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        // 清空缓存
        // 删除文件夹里面所有文件
        [HKFileTool removeDirectoryPath:HKFileCachePath];
        _totalSize = 0;
        [self.tableView reloadData];
    }

     

     

     

     

     

  • 相关阅读:
    [Hibernate]
    asc.desc
    Could not obtain connection metadata
    java枚举类Enum方法简介(valueof,value,ordinal)
    maven3 手动安装本地jar到仓库
    maven命令大全
    如何正确遍历删除List中的元素,你会吗?
    Hibernate的session.createSQLQuery的几种查询方式
    Linux-github 搭建静态博客
    我所写的CNN框架 VS caffe
  • 原文地址:https://www.cnblogs.com/StevenHuSir/p/CalculateAppCache.html
Copyright © 2020-2023  润新知