Xcode计算缓存文件大小和清除缓存

//获得缓存路径
self.cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject;

/***********************   缓存管理  ***********************/
#pragma mark 单个文件的大小
+ (long long)fileSizeAtPath:(NSString *)filePath {
    //创建文件管理对象
    NSFileManager* manager = [NSFileManager defaultManager];
    //判断该文件是否存在
    if ([manager fileExistsAtPath:filePath]){
        //返回该文件大小
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}
#pragma mark 遍历文件夹获得文件夹大小,返回多少M
+ (CGFloat)folderSizeAtPath:(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){
        //各个文件路径
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize / (1024.0*1024.0);
}

#pragma mark 清理缓存文件
+ (void)clearCache:(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];
        }
    }

     //这是SDWebImage里的方法, 创建单例并调用清除图片方法
    [[SDImageCache sharedImageCache] cleanDisk];

}


原文地址:https://www.cnblogs.com/moxiaoyan33/p/5309254.html