iOS清除缓存

#pragma mark - 第一步,计算缓存文件的大小


//首先获取缓存文件的路径

-(NSString *)getPath

{

//沙盒目录下library文件夹下的cache文件夹就是缓存文件夹

NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

return path;

}

-(CGFloat)folderSizeWithPath:(NSString *)path

{

//初始化文件管理类

NSFileManager * fileManager = [NSFileManager defaultManager];

float folderSize = 0.0;

if ([fileManager fileExistsAtPath:path])

{

//如果存在

//计算文件的大小

NSArray * fileArray = [fileManager subpathsAtPath:path];

for (NSString * fileName in fileArray)

{

//获取每个文件的路径

NSString * filePath = [path stringByAppendingPathComponent:fileName];

//计算每个子文件的大小

long fileSize = [fileManager attributesOfItemAtPath:filePath error:nil].fileSize;//字节数

folderSize = folderSize + fileSize / 1024.0 / 1024.0;

}

//删除缓存文件

[self deleteFileSize:folderSize];

return folderSize;

}

return 0;

}


#pragma mark - 弹出是否删除的一个提示框,并且告诉用户目前有多少缓存


-(void)deleteFileSize:(CGFloat)folderSize

{

if (folderSize > 0.01)

{

UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:[NSString stringWithFormat:@"缓存大小:%.2fM,是否清除?",folderSize] delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

[alertView show];

}

else

{

UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"缓存已全部清理" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];

[alertView show];

}

}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex

{

if (buttonIndex == 1)

{

//彻底删除文件

[self clearCacheWith:[self getPath]];

}

}


-(void)clearCacheWith:(NSString *)path

{

NSFileManager * fileManager = [NSFileManager defaultManager];

if ([fileManager fileExistsAtPath:path])

{

NSArray * fileArray = [fileManager subpathsAtPath:path];

for (NSString * fileName in fileArray)

{

//可以过滤掉特殊格式的文件

if ([fileName hasSuffix:@".png"])

{

NSLog(@"不删除");

}

else

{

//获取每个子文件的路径

NSString * filePath = [path stringByAppendingPathComponent:fileName];

//移除指定路径下的文件

[fileManager removeItemAtPath:filePath error:nil];

}

}

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.点击单元格弹出提示 NSString *str = [self countCacheSize]; NSStri...
    滴答大阅读 316评论 0 3
  • 计算单个文件大小 计算目录大小 清除缓存文件 数据存储到iCloud
    没能唱给你的歌曲阅读 3,379评论 0 2
  • 27、ViewController的didReceiveMemoryWarning是在什么时候调用的?默认的操作是...
    烟雨平生花飞舞阅读 647评论 0 1
  • iOS开发系列--网络开发 概览 大部分应用程序都或多或少会牵扯到网络开发,例如说新浪微博、微信等,这些应用本身可...
    lichengjin阅读 3,773评论 2 7
  • 在我们开发app的过程中,都会涉及到一个问题,那就是清除缓存,我们都知道,随着应用使用频率的增加,程序cache的...
    某某cp阅读 714评论 0 1