iOS 缓存清除方法

来源:互联网 发布:海文网络班班代 编辑:程序博客网 时间:2024/05/29 05:58
没有固定的方法,你既然有做对应的缓存机制,这个机制就应该有清除缓存的方法。例如如果你使用某个第三方的图片库,这个库有缓存机制,那么它就应该提供对应的清除缓存的方法。你调用对应的方法进行清除,如果你自己有用到数据库,那么你就应该清除数据库里面的数据等等。

指的是沙盒下的缓存文件夹么

移动应用在处理网络资源时,一般都会做离线缓存处理,其中以图片缓存最为典型,其中很流行的离线缓存框架为SDWebImage。
但是,离线缓存会占用手机存储空间,所以缓存清理功能基本成为资讯、购物、阅读类app的标配功能。
今天介绍的离线缓存功能的实现,主要分为缓存文件大小的获取、删除缓存文件的实现。
获取缓存文件的大小
由于缓存文件存在沙箱中,我们可以通过NSFileManager API来实现对缓存文件大小的计算。

文件路径:
 NSString*cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES)objectAtIndex:0];

计算单个文件大小
1
2
3
4
5
6
7
8
+(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;
}

计算目录大小
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
+(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 +=[FileService fileSizeAtPath:absolutePath];
    }
   //SDWebImage框架自身计算缓存的实现
    folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
    return folderSize;
  }
  return 0;
}

清理缓存文件
同样也是利用NSFileManager API进行文件操作,SDWebImage框架自己实现了清理缓存操作,我们可以直接调用。
1
2
3
4
5
6
7
8
9
10
11
12
+(void)clearCache:(NSString *)path{
  NSFileManager *fileManager=[NSFileManager defaultManager];
  if ([fileManager fileExistsAtPath:path]) {
    NSArray *childerFiles=[fileManager subpathsAtPath:path];
    for (NSString *fileName in childerFiles) {
      //如有需要,加入条件,过滤掉不想删除的文件
      NSString *absolutePath=[path stringByAppendingPathComponent:fileName];
      [fileManager removeItemAtPath:absolutePath error:nil];
    }
  }
  [[SDImageCache sharedImageCache] cleanDisk];
  [[SDImageCache sharedImageCache] clearMemory];//添加这句话会清除头像的缓存不好,用时注意,在更换头像的时候清除之前头像的缓存,可以用这句话,在设置页最好不用
}

0 0