iOS计算缓存大小、清除缓存

来源:互联网 发布:js 页面加载隐藏div 编辑:程序博客网 时间:2024/05/09 08:43

获取缓存文件路径

(NSString *)getCachesPath{    // 获取Caches目录路径    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask,YES);    NSString *cachesDir = [paths objectAtIndex:0];    NSString *filePath = [cachesDir stringByAppendingPathComponent:@"myCache"];    return cachesDir;}

计算单个文件的大小

(long long)fileSizeAtPath:(NSString*)filePath{    NSFileManager* manager = [NSFileManager defaultManager];    if ([manager fileExistsAtPath:filePath]){        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];    }    return 0;}

遍历文件夹获得文件夹大小,返回多少M

(float)getCacheSizeAtPath:(NSString*)folderPath{    NSFileManager* manager = [NSFileManager defaultManager];    if (![manager fileExistsAtPath:folderPath]) return 0;    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];//从前向后枚举器    NSString* fileName;    long long folderSize = 0;    while ((fileName = [childFilesEnumerator nextObject]) != nil){        NSLog(@"fileName ==== %@",fileName);        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];        NSLog(@"fileAbsolutePath ==== %@",fileAbsolutePath);        folderSize += [self fileSizeAtPath:fileAbsolutePath];    }    NSLog(@"folderSize ==== %lld",folderSize);    return folderSize/(1024.0*1024.0);}

清除缓存

+(void)clearCacheAtPath:(NSString *)path{    NSFileManager *fileManager=[NSFileManager defaultManager];    if ([fileManager fileExistsAtPath:path]) {        NSArray *childerFiles=[fileManager subpathsAtPath:path];        for (NSString *fileName in childerFiles) {            //如有需要,加入条件,过滤掉不想删除的文件            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];            [fileManager removeItemAtPath:absolutePath error:nil];        }    }}
2 0