清除缓存数据的方法

本文介绍了一种在iOS应用中清除缓存数据的方法,通过使用SDWebImage库和自定义代码实现缓存大小的获取及彻底清除功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在做项目的时候,常常需要一个清除数据缓存的功能,下面的一些代码是我平常用的清除缓存的方法

#import "UIImageView+WebCache.h"
#import "SDImageCache.h"//包含头文件   借助于SDWebImage库
//创建一个button
UIButton *DelButton=[UIButton buttonWithType:UIButtonTypeCustom];
    DelButton.frame=CGRectMake(40, 100, 60, 40);
    [DelButton addTarget:self action:@selector(DelButton) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:DelButton];
-(void)DelButton{
UIActionSheet *sheet=[[UIActionSheet alloc] initWithTitle:[NSString stringWithFormat:@"删除缓存文件:%.2fM",[self getCachesSize]] delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"删除" otherButtonTitles:nil];
            [sheet showInView:self.view];
}
-(double)getCachesSize{
    //获取缓存数据
    double sdSize=[[SDImageCache sharedImageCache] getSize];
    NSString *myCachePath=[NSHomeDirectory() stringByAppendingFormat:@"/Library/Caches/MyCaches"];
    NSDirectoryEnumerator *enumerator=[[NSFileManager defaultManager] enumeratorAtPath:myCachePath];
    double mySize=0;
    for (NSString *fileName in enumerator) {
        NSString *filePath=[myCachePath stringByAppendingPathComponent:fileName];
        NSDictionary *dict=[[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        mySize +=dict.fileSize;
    }
    double totalSize=sdSize/1024/1024;//转化为M
    return totalSize;

}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
//清除缓存
    if (buttonIndex==actionSheet.destructiveButtonIndex) {
        [[SDImageCache sharedImageCache] clearMemory];
        [[SDImageCache sharedImageCache] clearDisk];
        NSString *myCachePath=[NSHomeDirectory() stringByAppendingFormat:@"/Library/Caches/MyCaches"];
        [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值