NSFileManager与沙盒 --- 清除缓存

思维导图:清除缓存整体思路

NSFileManager与沙盒 --- 清除缓存

一、沙盒的文件

1、Documents:存储用户常用的文件(比较小的文件,因为备份时会备份这个文件夹下的内容)

2、Library: 存储的是缓存文件或者说是下载的文件。

3、Tmp: 存储的是临时文件。

二、NSFileManager操作清除缓存

 方法一:计算所有文件夹大小及文件大小(会遍历文件夹中所有文件夹中的文件)

NSFileManager *mag = [NSFileManager defaultManager];
__block long long size = 0;
NSDirectoryEnumerator *enums = [mag enumeratorAtPath:dirPath];
for (NSString *subString in enums) {
    //用目录路径拼接文件管理目录中的子文件路径等到全路径,如dirPath/A,dirPath/B,这样的话就可以获取所有文件夹下内容的大小
    NSString *fullString = [dirPath stringByAppendingPathComponent:subString];
    //取出所有文件、文件夹的属性计算尺寸
    size += [mag attributesOfItemAtPath:fullString error:nil].fileSize;
    NSLog(@"%zd",size);
}

 方法二:计算所有文件的大小(不会遍历里面文件夹)

//subpathsAtPath:返回NSArray提供的所有内容和递归子路径路,意思是说比较耗时
NSArray *asg = [mag subpathsAtPath:dirPath];
      __block long long size = 0;
for (NSString *subString in asg) {
    //全路径,
    NSString *fullPath = [dirPath stringByAppendingPathComponent:subString];
    //文件的属性,遍历文件夹中所有文件或文件夹。
    NSDictionary *attri = [mag attributesOfItemAtPath:fullPath error:nil];
    size += [attri fileSize];
    NSLog(@"%.2lldM",size);
}

 三、封装成NSString的分类方法

    unsigned long long size = 0;
    NSFileManager *fileM = [NSFileManager defaultManager];
    NSDictionary *attri = [fileM attributesOfItemAtPath:self error:nil];
//    BOOL isExist = NO;
//    [fileM fileExistsAtPath:self isDirectory:&isExist];
//    if (isExist) {
//    } //这个方法也是判断文件夹是否存在

    if (attri.fileType == NSFileTypeDirectory) {//是否为文件夹
        NSDirectoryEnumerator *enums = [fileM enumeratorAtPath:self];
        for (NSString *subString in enums) {
            //用目录路径拼接文件管理目录中的子文件路径等到全路径,如dirPath/A,dirPath/B,这样的话就可以获取所有文件夹下内容的大小
            NSString *fullString = [self stringByAppendingPathComponent:subString];
            //取出所有文件、文件夹的属性计算尺寸
            size += [fileM attributesOfItemAtPath:fullString error:nil].fileSize;
        }
    }else{
        NSArray *files = [fileM subpathsAtPath:self];
        for (NSString *subString in files) {
            NSString *fullPath = [self stringByAppendingPathComponent:subString];
            size += [fileM attributesOfItemAtPath:fullPath error:nil].fileSize;
        }
    }
    return size;