iOS中计算磁盘缓存文件夹的大小

SDWebImage框架中在自动做磁盘缓存的过程中,底层实现了计算Cache的大小,框架的方法名称是getSize,但方法不容易被人理解,我就从新写了一下,附带注释

  基本思想: 1. 先取出的Cache,获取该文件的路径

                2. 利用NSFileManager,取出该文件下的所有子路径返回一个数组

      3.遍历数组,利用文件的fileSize属性,把每个子路径下文件的取出来累加,即为该文件夹的大小

      注意: 注意文件夹的隐藏文件,会使得到的文件大小出现偏差

             得到的大小为B,若是在苹果手机中,需转化M(需要除去(1000.0 * 1000.0))

// 获取cache文件夹路径

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

    // 创建文件管理者单粒(要想管理文件,必须使用NSFileManager)

    NSFileManager *mgr = [NSFileManager defaultManager];

    

    // 获取文件夹所有子路径数组:获取多级目录下文件路径

    NSArray *subpaths = [mgr subpathsAtPath:cachePath];

    

    // 遍历

    int totalSize = 0;

    for (NSString *subPath in subpaths) {

    //拼接每一条子路径

        NSString *filePath = [cachePath stringByAppendingPathComponent:subPath];

        

        // 判断是否是隐藏文件(.DS为苹果中的一种隐藏文件),若是隐藏文件,跳过该次执行,进入下次执行

        if ([filePath containsString:@".DS"]) continue;

        

        // 判断是否是文件夹

        BOOL isDirectory = NO;

  //如果文件不存在或者为文件夹,就跳过

        BOOL isExists = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory];

        if (!isExists || isDirectory) continue;

        

        // 获取文件属性(利用文件的fileSize属性)

       NSDictionary *attr = [mgr attributesOfItemAtPath:filePath error:nil];

        totalSize += [attr fileSize];

原文地址:https://www.cnblogs.com/muzichenyu/p/5988689.html