iOS开发之1行代码实现缓存计算及清除缓存

时间:2022-02-08 08:57:04

话不多说,直接撸代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//
// gzhCache.h
// cache
//
// Created by 郭志贺 on 2020/5/27.
// Copyright © 2020 郭志贺. All rights reserved.
//
 
#import <Foundation/Foundation.h>
 
NS_ASSUME_NONNULL_BEGIN
 
@interface gzhCache : NSObject
 
/// 计算缓存大小
+(float)filePath;
 
/// 清理缓存
+(void)clearCache;
@end
 
NS_ASSUME_NONNULL_END
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// gzhCache.m
// cache
//
// Created by 郭志贺 on 2020/5/27.
// Copyright © 2020 郭志贺. All rights reserved.
//
 
#import "gzhCache.h"
 
@implementation gzhCache
// 显示缓存大小
+ (float)filePath {
  NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
 
  return [ self folderSizeAtPath :cachPath];
}
//计算单个文件的大小
+ (long long) fileSizeAtPath:( NSString *) filePath{
  NSFileManager * manager = [ NSFileManager defaultManager ];
  if ([manager fileExistsAtPath :filePath]){
    return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ];
  }
  return 0 ;
}
//遍历文件夹获得文件夹大小,返回多少M
+ (float)folderSizeAtPath:(NSString *)folderPath{
  NSFileManager * manager = [ NSFileManager defaultManager ];
  if (![manager fileExistsAtPath :folderPath]) return 0 ;
  NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ];
  NSString * fileName;
  long long folderSize = 0 ;
  while ((fileName = [childFilesEnumerator nextObject ]) != nil ){
    NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName];
    folderSize += [ self fileSizeAtPath :fileAbsolutePath];
  }
  return folderSize/( 1024.0 * 1024.0 );
}
//清理缓存
+ (void)clearCache {
  NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ];
  NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath];
  NSLog ( @"cachpath = %@" , cachPath);
  for ( NSString * p in files) {
    NSError * error = nil ;
    NSString * path = [cachPath stringByAppendingPathComponent :p];
    if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) {
      [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error];
    }
  }
  [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject : nil waitUntilDone : YES ];
}
+ (void)clearCachSuccess {
  NSLog(@"清理成功");
}
@end

需要查询大小的地方使用:

?
1
NSString *str = [NSString stringWithFormat:@"%.2fM",[gzhCache filePath]];

清理的方法调用

?
1
[gzhCache clearCache];

 以上内容仅代表本菜鸟看法,复制可直接使用。如有不妥之处敬请告知。

好了,到此这篇iOS开发之1行代码实现缓存计算及清除缓存的文章就介绍到这了,更多相关iOS缓存计算及清除缓存内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/guozhihe/p/12973754.html