NSString+Extension.m

/**
 * 计算当前路径字符串指定的文件/文件夹大小
 * 文件/文件夹大小,-1代表指定的文件或文件夹路径不存在,以字节为单位
 */
- (NSInteger)fileSize {

    NSFileManager *mgr = [NSFileManager defaultManager];
    BOOL dir = NO;
    BOOL exists = [mgr fileExistsAtPath:self isDirectory:&dir];
    if (!exists) {
        return -1;
    }
    
    if (dir) { // 目录
        NSInteger totalByteSize = 0;
        NSArray *subPaths = [mgr subpathsAtPath:self]; // 单个文件路径
        for (NSString *subPath in subPaths) {
            // 计算完整路径下的文件大小,并累加
            totalByteSize += [[mgr attributesOfItemAtPath:[self stringByAppendingPathComponent:subPath] error:nil][NSFileSize] integerValue];
        }
        return totalByteSize;
    } else { // 文件
        return [[mgr attributesOfItemAtPath:self error:nil][NSFileSize] integerValue] ;
    }
    
}

 

移除某个文件或文件夹:

// 清除缓存
- (void)clearCache {
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSFileManager *mgr = [NSFileManager defaultManager];
    [mgr removeItemAtPath:cachePath error:nil];
    
}

 

 

最终效果:

新浪微博客户端(62)-计算某个文件或文件夹的大小

 

新浪微博客户端(62)-计算某个文件或文件夹的大小

 

相关文章:

  • 2022-12-23
  • 2022-03-03
  • 2021-12-07
  • 2021-11-21
  • 2021-07-12
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-03
  • 2021-04-02
  • 2021-04-29
  • 2021-10-09
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案