美文网首页
iOS之缓存清理的实现

iOS之缓存清理的实现

作者: ethan_cun | 来源:发表于2016-11-10 08:10 被阅读20次

    一、一般Xcode的缓存分为两大块:
    一是自己工程缓存的一些数据;第二如果使用了SDWebImage则还需要清理图片缓存。

    二、计算单个文件的大小

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

    三、计算文件夹的大小(含SDWenImage的图片缓存)

    -(float)folderSizeAtPath:(NSString *)path
    {
        NSFileManager *fileManager=[NSFileManager defaultManager]; 
        NSString *cachePath=    [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]; 
        cachePath=[cachePath stringByAppendingPathComponent:path]; 
        long long folderSize=0; 
    if ([fileManager fileExistsAtPath:cachePath]) { 
        NSArray *childerFiles=[fileManager subpathsAtPath:cachePath];
        for (NSString *fileName in childerFiles) {
        NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName]; 
        long long size=[self fileSizeAtPath:fileAbsolutePath]; 
        folderSize += size;        
        NSLog(@"fileAbsolutePath=%@",fileAbsolutePath); 
    } 
    //SDWebImage框架自身计算缓存的实现
       folderSize+=[[SDImageCache sharedImageCache] getSize]; 
        return folderSize/1024.0/1024.0;
     }
     return 0;
    }
    

    四、得到了缓存大小最后就是清除缓存了

    //同样也是利用NSFileManager API进行文件操作,SDWebImage框架自己实现了清理缓存操作,我们可以直接调用。
    -(void)clearCache:(NSString *)path{ 
        NSString *cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
         cachePath=[cachePath stringByAppendingPathComponent:path]; 
        NSFileManager *fileManager=[NSFileManager defaultManager];
         if ([fileManager fileExistsAtPath:cachePath]) {
         NSArray *childerFiles=[fileManager subpathsAtPath:cachePath]; 
        for (NSString *fileName in childerFiles) { 
        //如有需要,加入条件,过滤掉不想删除的文件 
        NSString *fileAbsolutePath=[cachePath stringByAppendingPathComponent:fileName];     
        NSLog(@"fileAbsolutePath=%@",fileAbsolutePath);     
        [fileManager removeItemAtPath:fileAbsolutePath error:nil];   
      }
     }
       [[SDImageCache sharedImageCache] cleanDisk];
    }
    

    五、个人经验总结(坑)
    1.做缓存清理最好封装一个单例管理对象,对象要保证唯一性;
    2.缓存路径可以封装一下,这样在外面调用的时候就可以不用再传路径了;
    3.清理的过程涉及到遍历子路径,当缓存多的时候,会有很长的耗时操作,所以这时应该讲遍历删除的过程全部写到新开辟的子线程中去,然后回到主线程刷新UI界面;

    六、完了。

    相关文章

      网友评论

          本文标题:iOS之缓存清理的实现

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