iOS数据缓存和清除

移动应用在处理网络资源时,通常都会作离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage。java

可是,离线缓存会占用手机存储空间,因此缓存清理功能基本成为资讯、购物、阅读类app的标配功能。web

今天介绍的离线缓存功能的实现,主要分为缓存文件大小的获取、删除缓存文件的实现。 缓存

获取缓存文件的大小网络

因为缓存文件存在沙箱中,咱们能够经过NSFileManager API来实现对缓存文件大小的计算。咱们的应用的缓存都存在caches文件夹下 通常的缓存指的是caches文件夹下的文件大小 以及使SDWebImage产生的图片缓存 下面是计算缓存的步骤app

获得caches文件的路径框架

NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

计算单个文件大小 svg

- (float)fileSizeAtPath:(NSString *)path{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        long long size=[fileManager attributesOfItemAtPath:path error:nil].fileSize;
        return size/1024.0/1024.0;
    }
    return 0;
}

计算cahces文件下全部文件的大小以及SDWebImage产生的图片缓存的大小工具

// 计算目录大小
- (float)folderSizeAtPath:(NSString *)path {
    NSFileManager *fileManager=[NSFileManager defaultManager];
    float folderSize;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles = [fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            folderSize += [self fileSizeAtPath:absolutePath];
        }
        //SDWebImage框架自身计算缓存的实现
        folderSize += [[SDImageCache sharedImageCache] getSize] /1024.0/1024.0;
        // NSLog(@"%.2f", folderSize);
        return folderSize;
    }
    return 0;
}

清理缓存文件ui

一样也是利用NSFileManager API进行文件操做,SDWebImage框架本身实现了清理缓存操做,咱们能够直接调用。 spa

-(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];
        }
    }
    [[SDImageCache sharedImageCache] cleanDisk];
}

若是能够,将这些方法封装到一个类中,使用类方法调用更好。

最新更新:

咱们能够封装成一个工具类: ClearCacheTool类。

ClearCacheTool.h文件:

#import <Foundation/Foundation.h>

@interface ClearCacheTool : NSObject

/*s* * 获取path路径下文件夹的大小 * * @param path 要获取的文件夹 路径 * * @return 返回path路径下文件夹的大小 */
+ (NSString *)getCacheSizeWithFilePath:(NSString *)path;

/** * 清除path路径下文件夹的缓存 * *  @param path 要清除缓存的文件夹 路径 * *  @return 是否清除成功 */
+ (BOOL)clearCacheWithFilePath:(NSString *)path;

ClearCacheTool.m文件:

#import "ClearCacheTool.h"

@implementation ClearCacheTool

#pragma mark - 获取path路径下文件夹大小
+ (NSString *)getCacheSizeWithFilePath:(NSString *)path{

    // 获取“path”文件夹下的全部文件
    NSArray *subPathArr = [[NSFileManager defaultManager] subpathsAtPath:path];

    NSString *filePath  = nil;
    NSInteger totleSize = 0;

    for (NSString *subPath in subPathArr){

        // 1. 拼接每个文件的全路径
        filePath =[path stringByAppendingPathComponent:subPath];
        // 2. 是不是文件夹,默认不是
        BOOL isDirectory = NO;
        // 3. 判断文件是否存在
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];

        // 4. 以上判断目的是忽略不须要计算的文件
        if (!isExist || isDirectory || [filePath containsString:@".DS"]){
            // 过滤: 1. 文件夹不存在 2. 过滤文件夹 3. 隐藏文件
            continue;
        }

        // 5. 指定路径,获取这个路径的属性
        NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        /** attributesOfItemAtPath: 文件夹路径 该方法只能获取文件的属性, 没法获取文件夹属性, 因此也是须要遍历文件夹的每个文件的缘由 */

        // 6. 获取每个文件的大小
        NSInteger size = [dict[@"NSFileSize"] integerValue];

        // 7. 计算总大小
        totleSize += size;
    }

    //8. 将文件夹大小转换为 M/KB/B
    NSString *totleStr = nil;

    if (totleSize > 1000 * 1000){
        totleStr = [NSString stringWithFormat:@"%.2fM",totleSize / 1000.00f /1000.00f];

    }else if (totleSize > 1000){
        totleStr = [NSString stringWithFormat:@"%.2fKB",totleSize / 1000.00f ];

    }else{
        totleStr = [NSString stringWithFormat:@"%.2fB",totleSize / 1.00f];
    }

    return totleStr;
}


#pragma mark - 清除path文件夹下缓存大小
+ (BOOL)clearCacheWithFilePath:(NSString *)path{

    //拿到path路径的下一级目录的子文件夹
    NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];

    NSString *filePath = nil;

    NSError *error = nil;

    for (NSString *subPath in subPathArr)
    {
        filePath = [path stringByAppendingPathComponent:subPath];

        //删除子文件夹
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (error) {
            return NO;
        }
    }
    return YES;
}