用NSFileManager计算缓存大小、清除缓存

清除缓存方法:

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值