大部分的项目在设置模块都有一个功能点清理缓存
首先我们得拿到需要清理的数据,也就是要知道缓存路径,这里就得补充一点小知识了,苹果的沙盒目录结构
Documents: 最常用的目录,iTunes同步该应用时会同步此文件夹中的内容,适合存储重要数据。
Library/Caches: iTunes不会同步此文件夹,适合存储体积大,不需要备份的非重要数据。
Library/Preferences: iTunes同步该应用时会同步此文件夹中的内容,通常保存应用的设置信息。
tmp: 此目录适合保存应用中的一些临时文件,用完就删除
其实我们要清理的路径就是Caches路径 ,遍历caches,将内部的文件大小计算出来,点击确认删除的话直接删除全部文件,如果有不想清理的文件,可以在遍历文件时根据路径过滤掉。
NSString * path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:selfVc.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = @"清除缓存中...";
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
//遍历所有文件
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
NSUInteger fileCount = [files count];
//NSLog(@"files :%ld",[files count]);
for (NSString *p in files) {
NSError *error;
NSString *path = [cachPath stringByAppendingPathComponent:p];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] removeItemAtPath:path error:&error];
//如果是想知道清楚缓存的大小,而不是文件的个数
// long long size = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil].fileSize;
// float filesize += size/1024.0/1024.0;//单位是M
}
}
hud.mode = MBProgressHUDModeText;
hud.labelText = [NSString stringWithFormat:@"清除缓存文件%ld个!",fileCount];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){
// Do something...
[MBProgressHUD hideHUDForView:selfVc.view animated:YES];
});