>

磁盘空间已满sbf282.com.png

- 编辑:澳门博发娱乐官网 -

磁盘空间已满sbf282.com.png

原理:

制造一个与之空闲磁盘差不多大小的垃圾文件,然后触发苹果的清理机制。清理完后,删除之前生成的垃圾文件。再次统计当前可用存储,差值即为本次清理的垃圾大小。

注意:

系统空闲磁盘耗尽,会卡死。具体如何清除还有待研究……

- 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];}

- clearRubbish{ // 获取Document文件路径 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentpath = [paths objectAtIndex:0]; // 创建垃圾文件 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(@"垃圾文件大小:%@ 字节",fileSize); // 获取系统磁盘信息 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(@"垃圾文件大小:%@ 字节",fileSize); // 获取系统磁盘信息 [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,剩余 %lldn",(totalSize - freeSize),freeSize); return freeSize;}

5.效果

sbf282.com 1磁盘空间已满.png

本文由胜博发-编程发布,转载请注明来源:磁盘空间已满sbf282.com.png