iOS 設(shè)置中清除緩存功能

絕大多數(shù)應(yīng)用中都存在著清楚緩存的功能,形形色色,各有千秋,現(xiàn)為大家介紹一種最基礎(chǔ)的清除緩存的方法。清除緩存基本上都是在設(shè)置界面的某一個(gè)Cell,于是我們可以把清除緩存封裝在某一個(gè)自定義Cell中,如下圖所示:


清除緩存

具體步驟

使用注意:過程中需要用到第三方庫,請?zhí)崆鞍惭b好:SDWebImage、SVProgressHUD。

1. 創(chuàng)建自定義Cell,命名為GYLClearCacheCell

重寫initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier方法,設(shè)置基本內(nèi)容,如文字等等;主要代碼如下:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
  {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
       // 設(shè)置加載視圖
        UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [loadingView startAnimating];
        self.accessoryView = loadingView;

        //設(shè)置文字
        self.textLabel.text = @"清楚緩存";
        self.detailTextLabel.text = @"正在計(jì)算"; 
  }
    return self;
}

2. 計(jì)算緩存文件大小

緩存文件包括兩部分,一部分是使用SDWebImage緩存的內(nèi)容,其次可能存在自定義的文件夾中的內(nèi)容(視頻,音頻等內(nèi)容),于是計(jì)算要分兩部分,主要代碼如下:

unsigned long long size =
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"CustomFile"].fileSize;
//fileSize是封裝在Category中的。

size += [SDImageCache sharedImageCache].getSize;   //CustomFile + SDWebImage 緩存

//設(shè)置文件大小格式
NSString sizeText = nil;
if (size >= pow(10, 9)) {
  sizeText = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
}else if (size >= pow(10, 6)) {
  sizeText = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
}else if (size >= pow(10, 3)) {
  sizeText = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
}else {
  sizeText = [NSString stringWithFormat:@"%zdB", size];
}

上述兩個(gè)方法都是在主線程中完成的,如果緩存文件大小非常大的話,計(jì)算時(shí)間會比較長,會導(dǎo)致應(yīng)用卡死,考慮到該問題,因此需要將上述代碼放到子線程中完成。

3. 添加手勢監(jiān)聽

對于監(jiān)聽點(diǎn)擊Cell可以使用代理也可以使用手勢監(jiān)聽,為了將完整的功能封裝到自定義Cell中,于是我們使用手勢監(jiān)聽的方法來監(jiān)聽點(diǎn)擊Cell。

//計(jì)算完成后,回到主線程繼續(xù)處理,顯示文件大小,除去加載視圖,顯示箭頭,添加點(diǎn)擊事件
dispatch_async(dispatch_get_main_queue(), ^{
                
  self.detailTextLabel.text = [NSString stringWithFormat:@"%@",sizeText];
  self.accessoryView = nil;
  self.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
  [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clearCacheClick)]];          
 });

4. 清除緩存

清除緩存也是分為兩部分,一是清除SDWebImage的緩存,二是清除自定義文件緩存,主要代碼如下:

- (void)clearCacheClick
{
    [SVProgressHUD showWithStatus:@"正在清除緩存···"];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
           
            NSFileManager *mgr = [NSFileManager defaultManager];
            [mgr removeItemAtPath:GYLCustomFile error:nil];
            [mgr createDirectoryAtPath:GYLCustomFile withIntermediateDirectories:YES attributes:nil error:nil];
            
            dispatch_async(dispatch_get_main_queue(), ^{
               
                [SVProgressHUD dismiss];
                
                // 設(shè)置文字
                self.detailTextLabel.text = nil;               
            });         
        });
    }];
}

注意點(diǎn):SDWebImage清除緩存是在子線程中進(jìn)行的,清除自定義文件內(nèi)容應(yīng)該也放在子線程中(刪除大文件可能比較耗時(shí)),為了保證兩者不沖突,可以將刪除自定義文件內(nèi)容放在SDWebImage緩存清除完畢之后進(jìn)行,然后再回到主線程操作。

5. 其他注意點(diǎn)

a. 在計(jì)算文件大小過程中應(yīng)該是不允許點(diǎn)擊Cell的,如果有設(shè)置Cell的didSelectRowAtIndexPath方法,那么會導(dǎo)致手勢監(jiān)聽不能使用。于是需要在計(jì)算時(shí)不能點(diǎn)擊Cell。
b. 設(shè)置userInteractionEnabled=NO應(yīng)放在設(shè)置文字之后,否則textLabel將顯示為灰色。
c. 當(dāng)計(jì)算文件大小沒有結(jié)束的時(shí),這個(gè)時(shí)候點(diǎn)擊返回,自定義Cell不會被銷毀,他會執(zhí)行完剩下的代碼,可以使用dealloc方法來驗(yàn)證,在此情況下,可以使用弱引用的self來解決。
d. 當(dāng)設(shè)置界面的cell比較多時(shí),如果還在計(jì)算緩存大小時(shí),清除緩存的cell從視圖中消失,那么加載視圖動(dòng)畫就會被停止,當(dāng)返回到清除緩存cell時(shí),看不到加載動(dòng)畫。解決方案兩種方法:一個(gè)是在cell創(chuàng)建的代理方法中重新開啟動(dòng)畫;另一個(gè)是封裝到layoutSubviews方法中。

6. 使用

創(chuàng)建GYLSettingViewController繼承自UITableViewController;首先為自定義Cell注冊;其次在數(shù)據(jù)源方法中使用自定義Cell;具體代碼如下:

#import "GYLSettingViewController.h"
#import "GYLClearCacheCell.h"

@implementation GYLSettingViewController

static NSString * const GYLClearCacheCellID = @"ClearCache";
static NSString * const GYLSettingCellID = @"Setting";

- (instancetype)init
{
    return [self initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = GYLBGColor;
    self.navigationItem.title = @"設(shè)置";
    
    [self.tableView registerClass:[GYLClearCacheCell class] forCellReuseIdentifier:GYLClearCacheCellID];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:GYLSettingCellID];    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{  
    if (indexPath.section == 0 && indexPath.row == 0) {
        return [[GYLClearCacheCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:GYLClearCacheCellID];     
    }
       
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:GYLSettingCellID];
    cell.textLabel.text = [NSString stringWithFormat:@"section-%zd,row--%zd",indexPath.section,indexPath.row];
    return cell;
}

@end

7. 效果

計(jì)算文件大小
正在清除緩存
清除完畢
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,041評論 4 61
  • 設(shè)置界面?中清除緩存的處理---** 每個(gè)App幾乎都有清除緩存的功能** 一 手機(jī)上的磁盤緩存 == 從網(wǎng)絡(luò)上下...
    Tuberose閱讀 4,880評論 12 119
  • 春節(jié)假期,收到選修作業(yè),寫一個(gè)人。覺得這個(gè)題目太棒了,很早就對姐姐的歷程感興趣,因?yàn)榻憬阋恢倍际切闹械陌駱?,無論是...
    斯嘉麗薇閱讀 541評論 0 1
  • 孤獨(dú)真的是一個(gè)人的開始嗎? 高中的時(shí)候有位英語老師說過你高中沒有個(gè)一兩個(gè)好朋友,在大學(xué)就更不可能了。除非宿舍的人都...
    蛋丹閱讀 167評論 0 0
  • 中午吃過飯,跟小爺約定好玩半個(gè)小時(shí)就睡午覺,到了時(shí)間小爺卻開啟了你追我躲的模式,各種藏,讓你去抓他。 早起六點(diǎn)就起...
    第一期_阿皎閱讀 280評論 0 0

友情鏈接更多精彩內(nèi)容