您的位置:首页 > 其它

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

2016-12-19 20:58 323 查看
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];

}


最终效果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: