iOS-缓存的清理

作者: iSongWei | 来源:发表于2016-09-06 14:34 被阅读39次

    不积跬步,无以至千里
    不积小流,无以成江海

    具体目录参考iOS-沙盒机制存放文件

    • 计算单个文件的�大小
    -(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;
    }
    
    • 目录文件的大小
    -(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;
        return folderSize;
        }
        return 0;
    }
    
    • 缓存的清理
    -(void)clearCache:(NSString *)path{
    
        //NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
        //NSString *path = [paths lastObject];
      
        NSFileManager *fileManager=[NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:path]) {
            NSArray *childerFiles=[fileManager subpathsAtPath:path];
            for (NSString *fileName in childerFiles) {
            //删除所有文件
            NSError *error;
            NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
            [fileManager removeItemAtPath:absolutePath error:&error];
            }
        }
        //一般有用到SDWebImage可以用
        //#import "SDImageCache.h"
        [[SDImageCache sharedImageCache] cleanDisk];
    
    }
    

    相关文章

      网友评论

        本文标题:iOS-缓存的清理

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