第一种简便的方法
unsigned long long size = 0;
NSString * cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;
NSString * dirpath = [cachePath stringByAppendingPathComponent:@"default"];
NSFileManager * mgr = [NSFileManager defaultManager];
NSArray * subpaths = [mgr subpathsAtPath:dirpath];
// NSDirectoryEnumerator * subpaths = [mgr enumeratorAtPath:dirpath]; 遍历器 / 迭代器
for (NSString * subpath in subpaths) {
NSString * fullsubpath = [dirpath stringByAppendingPathComponent:subpath];
size += [mgr attributesOfItemAtPath:fullsubpath error:nil].fileSize;
}
NSLog(@"%llu",size);
NSLog(@"%f",size*1.0/1000/1000);
<br />
<br />
第二种 可以获取文件或者文件夹的大小
.h
#import <Foundation/Foundation.h>
@interface NSString (XMGExtension)
- (unsigned long long)fileSize;
@end
.m
#import "NSString+XMGExtension.h"
@implementation NSString (XMGExtension)
- (unsigned long long)fileSize
{
// 总大小
unsigned long long size = 0;
// 文件管理者
NSFileManager *mgr = [NSFileManager defaultManager];
// 是否为文件夹
BOOL isDirectory = NO;
// 路径是否存在
BOOL exists = [mgr fileExistsAtPath:self isDirectory:&isDirectory];
if (!exists) return size;
if (isDirectory) { // 文件夹
// 获得文件夹的大小 == 获得文件夹中所有文件的总大小
NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self];
for (NSString *subpath in enumerator) {
// 全路径
NSString *fullSubpath = [self stringByAppendingPathComponent:subpath];
// 累加文件大小
size += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize;
}
} else { // 文件
size = [mgr attributesOfItemAtPath:self error:nil].fileSize;
}
return size;
}
@end