ios 计算缓存大小

时间:2022-02-28 00:39:18

- (void)getSize2

{

// 图片缓存

NSUInteger size = [SDImageCache sharedImageCache].getSize;

//  NSLog(@"%zd %@", size, NSTemporaryDirectory());

NSFileManager *manager = [NSFileManager defaultManager];

// 文件夹

NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

NSString *cachePath = [caches stringByAppendingPathComponent:@"default/com.hackemist.SDWebImageCache.default"];

// 获得文件夹内部的所有内容

//    NSArray *contents = [manager contentsOfDirectoryAtPath:cachePath error:nil];

NSArray *subpaths = [manager subpathsAtPath:cachePath];

NSLog(@"%@", subpaths);

}

- (void)getSize

{

NSFileManager *manager = [NSFileManager defaultManager];

NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

NSString *cachePath = [caches stringByAppendingPathComponent:@"default/com.hackemist.SDWebImageCache.default"];

NSDirectoryEnumerator *fileEnumerator = [manager enumeratorAtPath:cachePath];

NSInteger totalSize = 0;

for (NSString *fileName in fileEnumerator) {

NSString *filepath = [cachePath stringByAppendingPathComponent:fileName];

//        BOOL dir = NO;

// 判断文件的类型:文件\文件夹

//        [manager fileExistsAtPath:filepath isDirectory:&dir];

//        if (dir) continue;

NSDictionary *attrs = [manager attributesOfItemAtPath:filepath error:nil];

if ([attrs[NSFileType] isEqualToString:NSFileTypeDirectory]) continue;

totalSize += [attrs[NSFileSize] integerValue];

}

NSLog(@"%zd", totalSize);

}