Implementation method of setting clear cache function in IOS


The vast majority of applications have the function of clear cache, which is diverse and has its own advantages. Now we introduce a most basic method to clear cache. Clearing the cache is basically in a cell in the setting interface, so we can encapsulate the clearing cache in a custom cell, as shown in the following figure:

Specific steps

Note: third party libraries need to be used in the process. Please install them in advance: sdwebimage and svprogresshud.

1. Create a custom cell named gylclearcachecell

Rewrite initwithstyle: (uitableviewcellstyle) style reuseidentifier: (nsstring *) reuseidentifier method to set basic contents, such as text, etc; The main codes are as follows:

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
  if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
    //Set load view
    UIActivityIndicatorView *loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [loadingView startAnimating];
    self.accessoryView = loadingView;
    //Set text
    self. textLabel. Text = @ "clear cache";
    self. detailTextLabel. Text = @ "calculating"; 
  return self;

2. Calculate cache file size

The cache file includes two parts. One part is the content cached by sdwebimage. Secondly, there may be the content in the customized folder (video, audio, etc.), so the calculation is divided into two parts. The main code is as follows:

unsigned long long size =
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"CustomFile"].fileSize;
//Filesize is encapsulated in category.
size += [SDImageCache sharedImageCache]. getSize;  // Customfile + sdwebimage cache
//Format file size
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];

The above two methods are completed in the main thread. If the cache file size is very large, the calculation time will be long and the application will get stuck. Considering this problem, the above code needs to be completed in the sub thread.

3. Add gesture monitoring

For monitoring click cells, you can use agents or gesture monitoring. In order to encapsulate the complete functions into custom cells, we use gesture monitoring to monitor click cells.

//After the calculation is completed, return to the main thread to continue processing, display the file size, remove the loading view, display the arrow, and add the click event
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. Clear cache

Clearing the cache is also divided into two parts. One is to clear the cache of sdwebimage and the other is to clear the cache of custom files. The main codes are as follows:

- (void)clearCacheClick
  [svprogresshud showwithstatus: @ "clearing cache ··"];
  [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];
        //Set text
        self.detailTextLabel.text = nil;        

Note: sdwebimage cache clearing is carried out in the sub thread. Clearing the contents of custom files should also be placed in the sub thread (deleting large files may be time-consuming). In order to ensure that the two do not conflict, you can delete the contents of custom files after sdwebimage cache clearing, and then return to the main thread.

5. Other precautions

a. In the process of calculating the file size, it should not be allowed to click cell. If the didselectrowatindexpath method of cell is set, gesture monitoring will not be used. Therefore, you cannot click cell during calculation.

b. Setting userinteractionenabled = no should be placed after the setting text, otherwise textlabel will be grayed out.

c. When the file size calculation is not finished, click return at this time. The custom cell will not be destroyed. It will execute the rest of the code. You can use dealloc method to verify. In this case, you can use self of weak reference to solve it.

d. When there are many cells in the setting interface, if the cells that clear the cache disappear from the view while calculating the cache size, the loading of view animation will be stopped. When returning to the clear cache cell, the loading animation will not be seen. There are two solutions: one is to restart the animation in the proxy method created by cell; The other is encapsulated in the layoutsubviews method.

6. Use

Create gylsettingviewcontroller, which inherits from uitableviewcontroller; First, register the user-defined cell; Secondly, the custom cell is used in the data source method; The specific codes are as follows:

#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 = @ "setting";
  [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;

7. Effect

Calculate file size

Clearing cache

Clear complete


The above is the implementation method of setting the clear cache function in IOS introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support to the developeppaer website!

Recommended Today

PostgreSQL regexp_ Matches replace like fuzzy query

I won’t talk more nonsense. Let’s look at the code directly~ Before modification: Select * from table name where field name like |#{parameter}|’%’ After modification: select *,regexp_ Matches (field name, #{parameter}) from table name Supplement: PostgreSQL implements fuzzy query regular expression Because the query operation of the database is relatively single, most of the fuzzy […]