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

 

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];
    
}

 

 

最终效果:

 

 

posted @ 2016-12-19 20:58  夜行过客  阅读(390)  评论(0编辑  收藏  举报