iOS 清除缓存

1.点击单元格弹出提示


NSString *str = [self countCacheSize];

NSString *casheStr = [NSString stringWithFormat:@"缓存大小为%@,确认清理吗?",str];

UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"清理缓存" message:casheStr delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];

[alertView show];

countCacheSize

- (NSString *)countCacheSize{

long long size = 0;

NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];

NSFileManager *fileMamager = [NSFileManager defaultManager];

//获取文件夹下的子路径

NSArray *pathArr = [fileMamager subpathsAtPath:path];

//拼接路径

for (NSString *subPath in pathArr) {

NSString *allPath = [path stringByAppendingPathComponent:subPath];

//计算文件的大小

NSDictionary *fileDic = [fileMamager attributesOfItemAtPath:allPath error:nil];

size += [fileDic fileSize];

}

NSString *cache = [NSString stringWithFormat:@"%.2fM",size/1000.0/1000.0];

return cache;

}

2.代理

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

if(buttonIndex ==1){

NSString *filepath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];

NSFileManager *fileManger = [NSFileManager defaultManager];

NSArray *arr = [fileManger subpathsAtPath:filepath];

for (NSString *subPath in arr) {

NSString *pathStr = [filepath stringByAppendingPathComponent:subPath];

[fileManger removeItemAtPath:pathStr error:nil];

//重新创建cache文件夹

[fileManger createDirectoryAtPath:filepath withIntermediateDirectories:YES attributes:nil error:nil];

[_tableView reloadRowsAtIndexPaths: @[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];

}

}

}

你可能感兴趣的:(iOS 清除缓存)