iOS之清除缓存
1 //清除缓存按钮的点击事件 2 3 - (void)putBufferBtnClicked:(UIButton *)btn{ 4 5 CGFloat size = [self folderSizeAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject] + [self folderSizeAtPath:NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject] + [self folderSizeAtPath:NSTemporaryDirectory()]; 6 7 8 9 NSString *message = size > 1 ? [NSString stringWithFormat:@"缓存%.2fM, 删除缓存", size] : [NSString stringWithFormat:@"缓存%.2fK, 删除缓存", size * 1024.0]; 10 11 12 13 UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:(UIAlertControllerStyleAlert)]; 14 15 16 17 UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction *action) { [self cleanCaches]; }]; 18 19 20 21 UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil]; 22 23 [alert addAction:action]; 24 25 [alert addAction:cancel]; 26 27 [self showDetailViewController:alert sender:nil]; 28 29 } 30 31 32 33 // 计算目录大小 34 35 - (CGFloat)folderSizeAtPath:(NSString *)path{ 36 37 // 利用NSFileManager实现对文件的管理 38 39 NSFileManager *manager = [NSFileManager defaultManager]; 40 41 CGFloat size = 0; 42 43 if ([manager fileExistsAtPath:path]) { 44 45 // 获取该目录下的文件,计算其大小 46 47 NSArray *childrenFile = [manager subpathsAtPath:path]; 48 49 for (NSString *fileName in childrenFile) { 50 51 NSString *absolutePath = [path stringByAppendingPathComponent:fileName]; 52 53 size += [manager attributesOfItemAtPath:absolutePath error:nil].fileSize; 54 55 } 56 57 // 将大小转化为M 58 59 return size / 1024.0 / 1024.0; 60 61 } 62 63 return 0; 64 65 } 66 67 // 根据路径删除文件 68 69 - (void)cleanCaches:(NSString *)path{ 70 71 // 利用NSFileManager实现对文件的管理 72 73 NSFileManager *fileManager = [NSFileManager defaultManager]; 74 75 if ([fileManager fileExistsAtPath:path]) { 76 77 // 获取该路径下面的文件名 78 79 NSArray *childrenFiles = [fileManager subpathsAtPath:path]; 80 81 for (NSString *fileName in childrenFiles) { 82 83 // 拼接路径 84 85 NSString *absolutePath = [path stringByAppendingPathComponent:fileName]; 86 87 // 将文件删除 88 89 [fileManager removeItemAtPath:absolutePath error:nil]; 90 91 } 92 93 } 94 95 } 96 97 //计算沙盒中文件的大小并删除沙盒中文件的例子: 98 99 - (void)cleanCaches{ 100 101 [self cleanCaches:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject]; 102 103 [self cleanCaches:NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject]; 104 105 [self cleanCaches:NSTemporaryDirectory()]; 106 107 } 108 109