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(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开发--清理缓存
ios文章原文 一段清理缓存的代码如下: dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) , ...
- iOS开发-清理缓存功能的实现
移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage. 但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯.购物.阅读类 ...
- ios 计算缓存大小并清理缓存
SDWebImage.WebView产生的缓存 1.计算缓存大小 //SDWebImage缓存大小 UILabel *cleanDetailText = [[UILabel alloc]init]; ...
- iOS 清理缓存功能实现第一种方法
添加一个提示框效果导入第三方MBProgressHUD #import "MBProgressHUD+MJ.h" /** * 清理缓存第一种方法 */ -(void)clearCa ...
- iOS 清理缓存功能的实现第二种方法
/** * 清理缓存第二种方法 * * @param sender <#sender description#> */ - (void)clearCache:(id)sender { // ...
- ios 清理缓存
//拿到要清理的路径,其实就是caches的路径,一般像这种很多地方都会用到的地方真好搞成宏,不过现在苹果不提倡用宏了 //在swift中可以定义成全局的常量 //遍历caches,将内部的文件大小计 ...
- iOS项目里面如何清理缓存
在正式讲解以前,请先看一下以下图片,在以下这款APP种设有清理缓存,开始我以为很复杂,在弄明白之后,其实就是几句代码就解决了. 在实际项目开发中,我们很多的文件都会缓存在沙盒里面,比如:照片 ...
- ios 清理缓存(EGO)
一段清理缓存的代码例如以下: dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,) , ^{ NSSt ...
- Linux 查看进程、清理缓存、查看磁盘空间、查看宽带的命令
一.查看进程 查看所有的进程命令:ps 查看指定的进程命令:ps -ef|grep java (java 指的是服务名称) 结束进程命令:kill -9 9028 (9028指的是PID) 二.清理 ...
随机推荐
- IOS原生地图与高德地图
原生地图 1.什么是LBS LBS: 基于位置的服务 Location Based Service 实际应用:大众点评,陌陌,微信,美团等需要用到地图或定位的App 2.定位方式 1.GPS定位 ...
- centos7 开放端口
开启端口 firewall-cmd --zone=public --add-port=80/tcp --permanent 命令含义: --zone #作用域 --add-port=80/tc ...
- Object类和常用方法
Object类是java语言的根类,要么是一个类的直接父类,要么就是一个类的间接父类.所有对象(包括数组)都实现这个类的方法. 引用数据类型:类/接口/数组,引用数据类型又称之位对象类,所谓的数组变量 ...
- springmvc拦截器验证登录时间
在前一篇[Filter实现用户名验证]的随笔里,记录了如何使用filter 这次增加了拦截器实现 ①filter实现用户登陆时验证用户名是否为null ②interceptor实现用户登陆时时间判断, ...
- C++编译期间字节序判断
当前常用的字节序一般就两种,大端序和小端序. 下面列出四种字节序的表达方式.在对应平台下,内存布局为{0x,00,0x01,0x02,0x03}的四字节,表示为十六进制的值就如下面代码所示的. END ...
- MySql: log 位置
mysql日志文件位置 登录mysql终端日志文件路径mysql> show variables like 'general_log_file';+------------------+---- ...
- websocket与socket.io
什么是Websocket? Websocket是一个独立于http的实时通信协议,最初是在HTML5中被引用进来的,在HTML5规范中作为浏览器与服务器的核心通信技术被嵌入到浏览器中.WebSocke ...
- js中JSON格式数据的转化
JSON.parse(STRING) => OBJECT JSON.stringify(OBJECT) => STRING
- 把 excel 和 mysq l数据库相互转换
不用代码轻松搞定,参考http://jingyan.baidu.com/article/fc07f9891cb56412ffe5199a.html 1.excel 转 mysql a.首先确认你的数据 ...
- 关于 android 的setOnItemClickListener 和 setOnItemLongClickListener 同时触发的解决方法
关于 android 的setOnItemClickListener 和 setOnItemLongClickListener 同时触发的解决方法. 其实方法也是很简单 的主要 setOnItemLo ...