作为一个开发者,对于缓存的清理也是理所应当的需要的。这次就简单的谈一下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(NSCachesDirectory, NSUserDomainMask, YES);
    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)机制和文件操作


iOS之 清理缓存的更多相关文章

  1. ios开发--清理缓存

    ios文章原文 一段清理缓存的代码如下: dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) , ...

  2. iOS开发-清理缓存功能的实现

    移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage. 但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯.购物.阅读类 ...

  3. ios 计算缓存大小并清理缓存

    SDWebImage.WebView产生的缓存 1.计算缓存大小 //SDWebImage缓存大小  UILabel *cleanDetailText = [[UILabel alloc]init]; ...

  4. iOS 清理缓存功能实现第一种方法

    添加一个提示框效果导入第三方MBProgressHUD #import "MBProgressHUD+MJ.h" /** * 清理缓存第一种方法 */ -(void)clearCa ...

  5. iOS 清理缓存功能的实现第二种方法

    /** * 清理缓存第二种方法 * * @param sender <#sender description#> */ - (void)clearCache:(id)sender { // ...

  6. ios 清理缓存

    //拿到要清理的路径,其实就是caches的路径,一般像这种很多地方都会用到的地方真好搞成宏,不过现在苹果不提倡用宏了 //在swift中可以定义成全局的常量 //遍历caches,将内部的文件大小计 ...

  7. iOS项目里面如何清理缓存

    在正式讲解以前,请先看一下以下图片,在以下这款APP种设有清理缓存,开始我以为很复杂,在弄明白之后,其实就是几句代码就解决了.      在实际项目开发中,我们很多的文件都会缓存在沙盒里面,比如:照片 ...

  8. ios 清理缓存(EGO)

    一段清理缓存的代码例如以下: dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,) , ^{ NSSt ...

  9. Linux 查看进程、清理缓存、查看磁盘空间、查看宽带的命令

    一.查看进程 查看所有的进程命令:ps 查看指定的进程命令:ps -ef|grep java (java 指的是服务名称) 结束进程命令:kill -9  9028 (9028指的是PID) 二.清理 ...

随机推荐

  1. iOS 浅谈:深.浅拷贝与copy.strong

    深.浅拷贝 copy mutableCopy NSString NSString *string = @"汉斯哈哈哈"; // 没有产生新对象 NSString *copyStri ...

  2. Facebook的Web开发三板斧:React.js、Relay和GraphQL

    2015-02-26 孙镜涛  InfoQ Eric Florenzano最近在自己的博客上发表了一篇题为<Facebook教我们如何构建网站>的文章,他认为软件开发有些时候需要比较大的跨 ...

  3. mysql load data 乱码

    解决方案: http://stackoverflow.com/questions/26256421/sql-load-data-infile-utf8-issue 即: load data local ...

  4. leveldb 性能、使用场景评估

    最近有个业务写远远大于读,读也集中在最近写入,这不很适合采用leveldb存储么,leveldb业界貌似ssdb用得挺广,花了两天时间就ssdb简单做下测试,以下总结. ssdb 是leveldb的r ...

  5. Bootstrap表单验证插件bootstrapValidator使用方法整理

    插件介绍 先上一个图: 下载地址:https://github.com/nghuuphuoc/bootstrapvalidator 使用方法:http://www.cnblogs.com/huangc ...

  6. http://blog.csdn.net/java2000_wl/article/details/8627874

    http://blog.csdn.net/java2000_wl/article/details/8627874

  7. 算法练习_图的连通性问题(JAVA)

    一.问题 1.问题描述: 有n个点(1...n),输入整数对(8,9),表示8,9点之间存在相互的连接关系. 动态连通性问题--编写一段程序过滤掉所以无意义的整数对,即为在不破坏图连通性的前提下,以最 ...

  8. connect mysql from another host

    vim /etc/mysql/my.cnf bind-address = 0.0.0.0 /etc/init.d/mysql restart mysql -uroot -p1234 # grant a ...

  9. js_原型

    原型是JavaScript中一个比较难理解的概念,原型相关的属性也比较多,对象有"prototype"属性,函数对象有"prototype"属性,原型对象有&q ...

  10. 正则表达式 判断 ip:端口 形式

    <html> <head> </head> <body> ip:port<input type="" name="z ...