iOS之 清理缓存

 

作为一个开发者,对于缓存的清理也是理所应当的需要的。这次就简单的谈一下iOS中对于缓存的清理方法。

我们清理缓存通常是在这三种方式下进行的:

(1)项目中的清理缓存按钮

(2)点击退出app按钮时清理缓存

(3)手动杀死进程  (说明:我们使用苹果手机时,大部分人并不喜欢每次都去点击退出app按钮。所以客户就有了在我们手动杀死进程时,对app进行缓存清理的要求)

接下来我们就从这三种方面来分析iOS的清理缓存。

 

我们知道iOS应用是在沙箱(sandbox)中的,在文件读写权限上受到限制,只能在几个目录下读写文件:

  • Documents:应用中用户数据可以放在这里,iTunes备份和恢复的时候会包括此目录
  • tmp:存放临时文件,iTunes不会备份和恢复此目录,此目录下文件可能会在应用退出后删除
  • Library/Caches:存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出删除

项目中的清理缓存按钮的代码就不列出了(我们可以在视图上直接添加Button,也可以在tableView上列出一个cell做清理缓存按钮),下面我直接给出清理缓存的代码

1、Caches目录的缓存一

#pragma mark - ************* Get cache size(计算数据缓存)*************

- (NSString *)getCacheSize{

    NSFileManager *fileManager = [NSFileManager defaultManager];

 

    NSArray *paths = nil;

    paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

    NSMutableString *cachepath = [paths objectAtIndex:0];

 

    NSError *error = nil;

    //文件夹下所有的目录和文件大小

    float cacheSize = 0.0f;

    //fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组

    NSArray *fileList = [fileManager contentsOfDirectoryAtPath:cachepath error:&error];

    BOOL isDir = NO;

 

    //在上面那段程序中获得的fileList中列出文件夹名

    for (NSString *file in fileList) {

        NSString *path = [cachepath stringByAppendingPathComponent:file];

        [fileManager fileExistsAtPath:path isDirectory:(&isDir)];

        //获取文件属性

        NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:path error:nil];//[[NSFileManager defaultManager] fileAttributesAtPath: path traverseLink: YES];

        //获取文件的创建日期

        NSDate *modificationDate = (NSDate*)[fileAttributes objectForKey: NSFileModificationDate];

 

        int timeSepearte = (int)[[NSDate date] timeIntervalSince1970]-(int)[modificationDate timeIntervalSince1970];

        if (timeSepearte>(3*86400)) {

            if ([fileManager isDeletableFileAtPath:path]) {

                [fileManager removeItemAtPath:path error:nil];

            }

        }else{

            if (isDir) {

                cacheSize = cacheSize + [self fileSizeForDir:path];

            }

        }

        isDir = NO;

    }

    NSString *cacheSizeString = @"";

    if (cacheSize >1024*1024) {

        float cacheSize_M = cacheSize/(1024*1024);

        cacheSizeString = [NSString stringWithFormat:@"%.1f M",cacheSize_M];

    }else if (cacheSize>1024&&cacheSize<1024*1024) {

        float cacheSize_KB = cacheSize/(1024);

        cacheSizeString = [NSString stringWithFormat:@"%.1f KB",cacheSize_KB];

    }else{

        float cacheSize_BYT = cacheSize/(1024);

        cacheSizeString = [NSString stringWithFormat:@"%.1f B",cacheSize_BYT];

    }

    

    return cacheSizeString;

}

 

-(float)fileSizeForDir:(NSString*)path//计算文件夹下文件的总大小

{

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    float size =0;

    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];

    for(int i = 0; i<[array count]; i++)

    {

        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];

        

        BOOL isDir;

        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )

        {

            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];

            size+= fileAttributeDic.fileSize;

        }

        else

        {

            [self fileSizeForDir:fullPath];

        }

    }

    return size;

}

2、Cache目录的缓存 二

#pragma mark - 计算缓存大小

- (NSString *)getCacheSize1

{

    //定义变量存储总的缓存大小

     long long cacheSize = 0;

     //01.获取当前图片缓存路径

    NSString *cacheFilePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];

    //02.创建文件管理对象

     NSFileManager *filemanager = [NSFileManager defaultManager];

 

         //获取当前缓存路径下的所有子路径

     NSArray *subPaths = [filemanager subpathsOfDirectoryAtPath:cacheFilePath error:nil];

 

        //遍历所有子文件

    for (NSString *subPath in subPaths) {

                 //1.拼接完整路径

             NSString *filePath = [cacheFilePath stringByAppendingFormat:@"/%@",subPath];

                //2.计算文件的大小

             long long fileSize = [[filemanager attributesOfItemAtPath:filePath error:nil]fileSize];

                 //3.加载到文件的大小

             cacheSize += fileSize;

         }

     float size_m = cacheSize/(1024*1024);

     return [NSString stringWithFormat:@"%.2fM",size_m];

    

}

清理缓存:

- (void)cleanCache

{

    //清理缓存

    NSFileManager *manager = [NSFileManager defaultManager];

    NSArray *paths = nil;

    paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectoryNSUserDomainMaskYES);

    NSMutableString *cachepath = [paths objectAtIndex:0];

    NSError *error = nil;

    NSArray *fileList = [manager contentsOfDirectoryAtPath:cachepath error:&error];

    for (NSString *file in fileList) {

        NSString *path = [cachepath stringByAppendingPathComponent:file];

        if ([manager isDeletableFileAtPath:path]) {

            [manager removeItemAtPath:path error:nil];

        }

    }

 

}

 3、NSUserDefaults (适合存储轻量级的本地数据),存储文件的清理

- (void)cleanCache

{

    NSUserDefaults *defatluts = [NSUserDefaults standardUserDefaults];

    NSDictionary *dictionary = [defatluts dictionaryRepresentation];

    for(NSString *key in [dictionary allKeys]){

        [defatluts removeObjectForKey:key];

        [defatluts synchronize];

    }

}

 以上就是关于iOS缓存的内容。

这篇不错的文章可以看下:

iOS学习之IOS沙盒(sandbox)机制和文件操作

 

 

 

posted @ 2016-11-23 11:30  WheatDen  阅读(2013)  评论(0编辑  收藏  举报