码迷,mamicode.com
首页 > 其他好文 > 详细

清除缓存功能的实现代码

时间:2015-06-10 22:26:58      阅读:518      评论:0      收藏:0      [点我收藏+]

标签:

缓存文件存储在沙盒文件夹Caches中,实现清除缓存,主要就是实现找到文件 - - 删除文件(其中涉及到计算文件大小)

以下是实现清除缓存的主要代码

//获取缓存路径

- (NSString *)getCache{

    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];

    NSLog(@"%@",cachePath);

    return cachePath;

}

//获取文件夹大小

- (CGFloat)folderSizeAtPath{

    //创建文件管理器

    NSFileManager *manager = [NSFileManager defaultManager];

    //获取文件夹路径

    NSString *folderPath = [self getCache];

    //如果缓存文件不存在,就返回0

    if (![manager fileExistsAtPath:folderPath]) {

        return 0;

    }

    //如果缓存文件存在就计算缓存文件的大小

    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];//从缓存路径中的文件数组得到枚举器

    NSString *fileName = nil;//定义一个空的文件名,用来获取枚举器中的文件名

    long long folderSize = 0;//定义并初始化文件大小为0

    while ((fileName = [childFilesEnumerator nextObject]) != nil) {

        //得到单个文件的绝对路径

        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];

        //定义单个文件变量并初始化为0

        float singleFileSize = 0.0;

        //如果该单个文件存在,获取单个文件的大小

        if ([manager fileExistsAtPath:fileAbsolutePath]) {

            //attributesOfItemAtPath:获取文件的属性

            singleFileSize = [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];

        }

        folderSize += singleFileSize;

    }

    return folderSize;

}

//清除缓存

- (void)clearCache{

    NSFileManager *manager = [NSFileManager defaultManager];

    NSString *floderPath = [self getCache];

    if ([manager fileExistsAtPath:floderPath]) {

        NSArray *childFiles = [manager subpathsAtPath:floderPath];

        for (NSString *fileName in childFiles) {

            NSString *absolutePath = [floderPath stringByAppendingPathComponent:fileName];

            [manager removeItemAtPath:absolutePath error:nil];

        }

    }

    [[SDImageCache sharedImageCache] cleanDisk];//因为我使用了SDWebImage这个第三方类,所以用这个类自带的方法实现

}

 

清除缓存功能的实现代码

标签:

原文地址:http://www.cnblogs.com/wangguimin/p/4567322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!