原理:
制造一個與之空閑磁盤差不多大小的垃圾文件,然后觸發(fā)蘋果的清理機制友绝。清理完后,刪除之前生成的垃圾文件。再次統(tǒng)計當前可用存儲,差值即為本次清理的垃圾大小爷光。
注意:
系統(tǒng)空閑磁盤耗盡灶芝,會卡死麦箍。具體如何清除還有待研究……
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 0, 200, 100)];
[button setTitle:@"清理緩存" forState:UIControlStateNormal];
button.backgroundColor = [UIColor greenColor];
[button addTarget:self action:@selector(clearRubbish) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
- (void)clearRubbish{
// 獲取Document文件路徑
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentpath = [paths objectAtIndex:0];
// 創(chuàng)建垃圾文件
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *filePath = [documentpath stringByAppendingPathComponent:@"rubbish.txt"];
if ([fileManager fileExistsAtPath:filePath]) {
[fileManager removeItemAtPath:filePath error:nil];
}
[fileManager createFileAtPath:filePath contents:[@"123" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];
NSDictionary *dict = [fileManager attributesOfItemAtPath:filePath error:nil];
NSString *fileSize = dict[@"NSFileSize"];
NSLog(@"制造垃圾文件前:\n");
NSLog(@"垃圾文件大小:%@ 字節(jié)",fileSize);
// 獲取系統(tǒng)磁盤信息
long long freeSpace = [self getSystemDiskInfo:documentpath];
// 快速制造垃圾文件
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
// 制造的垃圾文件比剩余磁盤空間大
[handle truncateFileAtOffset:freeSpace + 2];
dict = [fileManager attributesOfItemAtPath:filePath error:nil];
fileSize = dict[@"NSFileSize"];
NSLog(@"制造垃圾文件后:\n");
NSLog(@"垃圾文件大小:%@ 字節(jié)",fileSize);
// 獲取系統(tǒng)磁盤信息
[self getSystemDiskInfo:documentpath];
}
- (long long)getSystemDiskInfo:(NSString *)path{
NSDictionary *fileSysAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:path error:nil];
NSNumber *freeSpace = [fileSysAttributes objectForKey:NSFileSystemFreeSize];
NSNumber *totalSpace = [fileSysAttributes objectForKey:NSFileSystemSize];
long long freeSize = [freeSpace longLongValue];
long long totalSize = [totalSpace longLongValue];
NSLog(@"磁盤已使用 %lld,剩余 %lld\n",(totalSize - freeSize),freeSize);
return freeSize;
}
5.效果
磁盤空間已滿.png