// 清除缓存计算缓存大小
NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
CGFloat fileSize = [self folderSizeAtPath:cachPath];
// NSLog(@"~~%f",fileSize);
NSString *str = [NSString stringWithFormat:@"清除缓存%.1fM", fileSize];
//一、清理缓存cache文件夹,删除文件方法
-(void)clearCacheFlies
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除缓存成功" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[alert show];
[self.button1 setTitle:@"清除缓存0M" forState:UIControlStateNormal];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
// 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];
}
// NSLog(@"清理成功!");
}
});
}
//二、计算缓存cache文件夹下文件大小。
//单个文件的大小
- (long long)fileSizeAtPath:(NSString*) filePath{
NSFileManager* manager = [NSFileManager defaultManager];
if([manager fileExistsAtPath:filePath]){
return[[manager attributesOfItemAtPath:filePath error:nil] fileSize];
}
return 0;
}
//遍历文件夹获得文件夹大小,返回多少M
//设置folderPath为cache路径。
- (float) folderSizeAtPath:(NSString*) folderPath{
NSFileManager* manager = [NSFileManager defaultManager];
if(![manager fileExistsAtPath:folderPath])
return 0;
NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
NSString* fileName;
long long folderSize = 0;
while((fileName = [childFilesEnumerator nextObject]) != nil){
NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
folderSize += [self fileSizeAtPath:fileAbsolutePath];
}
return folderSize/(1024.0*1024.0); //得到缓存大小M
}
清除缓存计算缓存大小
最新推荐文章于 2024-09-20 09:18:43 发布