美文网首页
iOS开发_缓存处理

iOS开发_缓存处理

作者: DDB_CS | 来源:发表于2017-09-25 15:43 被阅读102次

    前言:最近在做一个练手小项目,由于项目中用到了如SDWebImage这类有缓存处理的框架,程序运行过程中会产生一些缓存,而我们知道很多app内都有获取缓存大小和清除缓存功能,于是我也动手做了一下。

    Snip20170925_1.png

    缓存存在原因:

    在程序运行过程中,我们可能需要多次请求同一个链接来获取数据,比如微博,微信朋友圈功能,但如果每次都发送一条新的请求来获取数据话会造成以下问题:

    (1) 用户流量的浪费

    (2) 程序响应速度不够快,用户体验差

    为了解决上面的问题,一般考虑对数据进行缓存.App需要缓存的主要原因就是改善应用所表现出的性能。将应用内容缓存起来可以支持离线、节省用户流量、减少加载时间等。缓存机制一般有两种。第一种是“按需缓存”,这种情况下应用缓存起请求应答,就和Web浏览器的工作原理一样;第二种是“预缓存”,这种情况是缓存全部内容(或者最近n条记录)以便离线访问。

    如何获取一个应用下的缓存数据以及计算缓存大小:

    我们知道一个app下会有个cache文件夹,专门来保存缓存文件,我们想要获取文件缓存,只需要获取cache文件夹路径,然后遍历文件夹路径下的所有文件(不包括文件本身,因为文件夹也是有大小的,获取文件夹本身的话会使获取的缓存大于真实缓存)并计算文件大小,即可算得缓存大小。这部分在很多框架中都会用到,比如SDWebImage中获取文件夹大小内容的代码实现如下:

    #pragma mark - Cache Info
    
    - (NSUInteger)getSize {
        __block NSUInteger size = 0;
        dispatch_sync(self.ioQueue, ^{
            // 枚举路径下的所有子文件
            NSDirectoryEnumerator *fileEnumerator = [_fileManager enumeratorAtPath:self.diskCachePath];
            for (NSString *fileName in fileEnumerator) {
                NSString *filePath = [self.diskCachePath stringByAppendingPathComponent:fileName];
              // 使用文件管理者获取文件属性
                NSDictionary<NSString *, id> *attrs = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
                size += [attrs fileSize];
            }
        });
        return size;
    }
    

    因此我们参考这个代码,将目标目录替换成cache文件夹,由于缓存可能很大,读取文件是个耗时操作,所以我们开启子线程处理获取缓存大小操作,当执行完成,用block将结果返回出去,代码实现如下:

    + (void)getFileSize:(NSString *)cachePath completion:(void (^)(NSInteger))completion {
        
        // 1.创建文件管理者对象
        NSFileManager *mgr = [NSFileManager defaultManager];
        
        // 异常处理
        BOOL isDirectory;
        [mgr fileExistsAtPath:cachePath isDirectory:&isDirectory];
        if (!isDirectory) {
            NSException *exp = [NSException exceptionWithName:@"invalid cache directory" reason:@"笨蛋,要传入一个文件路径" userInfo:nil];
            [exp raise];
        }
        
        // 2.获取缓存目录下的所有文件
        NSArray *pathArr = [mgr subpathsAtPath:cachePath];
        
        
        
        // 开启子线程处理耗时操作
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSInteger totalSize = 0;// 统计文件总大小
            // 3.遍历文件目录下的所有文件
            for (NSString *path in pathArr) {
                
                // 4.拼接文件真实路径
                NSString *filePath = [cachePath stringByAppendingPathComponent:path];
                
                // 5.判断是否为文件夹
                BOOL isExist;
                BOOL isDirectory;
                isExist = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory];
                if (!isExist || isDirectory) continue;
                
                // 6.获取文件大小
                NSDictionary *attrs = [mgr attributesOfItemAtPath:filePath error:nil];
                totalSize += [attrs fileSize];
    
                
                // 将获取到的文件传递出去
                dispatch_sync(dispatch_get_main_queue(), ^{
                    if (completion) {
                        completion(totalSize);
                    }
                });
                
            }
        });
    }
    
    

    如何清除缓存

    与获取缓存的思路相同,遍历所有文件,然后删除文件,代码简单易懂。话不多说,直接上代码:

    + (void)removeDirectory:(NSString *)filePath {
        
        // 1.创建文件管理者对象
        NSFileManager *mgr = [NSFileManager defaultManager];
        
        // 异常处理
        BOOL isDirectory;
        BOOL isExist;
        isExist = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory];
        if (!isDirectory || !isExist) {
            NSException *exp = [NSException exceptionWithName:@"invalid cache directory" reason:@"笨蛋,要传入一个文件路径,并且文件路径要存在!" userInfo:nil];
            [exp raise];
        }
        
        // 2.获取缓存目录下的所有文件夹
        NSArray *pathArr = [mgr contentsOfDirectoryAtPath:filePath error:nil];
        
        // 3.遍历文件目录下的所有文件
        for (NSString *path in pathArr) {
            
            // 4.拼接文件真实路径
            NSString *realPath = [filePath stringByAppendingPathComponent:path];
            
            // 5.删除文件
            [mgr removeItemAtPath:realPath error:nil];
            
        }
    }
    
    

    PS:最后如果各位大佬发现那里有问题欢迎批评指出,觉得有用点个喜欢~

    相关文章

      网友评论

          本文标题:iOS开发_缓存处理

          本文链接:https://www.haomeiwen.com/subject/ppcdextx.html