清除缓存方法:
removeItemAtPath:
计算缓存大小方法:
attributesOfItemAtPath:
使用了第三方SDWebImage
在ViewController.m中写如下代码:
在viewdidload:中写添加两个button的方法,button1可给视图添加图片,button2用来清除缓存、计算缓存大小
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
button1.backgroundColor = [UIColor redColor];
button1.frame = CGRectMake(0, 0, 100, 30);
[button1 setTitle:@"添加图片" forState:UIControlStateNormal];
[button1 addTarget:self action:@selector(handleButton1Action:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightItem = [[UIBarButtonItem alloc]initWithCustomView:button1];
self.navigationItem.rightBarButtonItem = rightItem;
UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
button2.backgroundColor = [UIColor redColor];
button2.frame = CGRectMake(0, 0, 100, 30);
[button2 setTitle:@"清除缓存" forState:UIControlStateNormal];
[button2 addTarget:self action:@selector(handleButton2Action:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithCustomView:button2];
self.navigationItem.leftBarButtonItem = leftItem;
}
button1的响应方法:
把图片添加到view上,同时在沙盒里的caches文件夹下,会有缓存文件
- (void)handleButton1Action:(UIButton *)sender{
UIImageView *imageview = [[UIImageView alloc]initWithFrame:self.view.bounds];
[imageview sd_setImageWithURL:[NSURL URLWithString:@"http://a.hiphotos.baidu.com/image/pic/item/b7003af33a87e950d59abd7e13385343fbf2b417.jpg"]];
[self.view addSubview:imageview];
}
button2的响应方法:
- (void)handleButton2Action:(UIButton *)sender{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];
NSLog(@"%@", cachesDir);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *files = [fileManager subpathsAtPath:cachesDir];
int theFileSize = 0;
for (NSString *file in files) {
//清除caches下所有缓存。需要拼接出完整路径
// [fileManager removeItemAtPath:[NSString stringWithFormat:@"%@/%@", cachesDir, file] error:nil];
//拼接出完整路径,通过路径取出每个文件的属性字典
NSDictionary *attributes = [fileManager attributesOfItemAtPath:[NSString stringWithFormat:@"%@/%@", cachesDir, file] error:nil];
//从属性字典里取出文件大小
theFileSize += [[attributes objectForKey:NSFileSize] intValue];
NSLog(@"%d", theFileSize);
}
NSLog(@"%fKB", theFileSize / 1024.0);
}