话不多说,直接撸代码
1 // 2 // gzhCache.h 3 // cache 4 // 5 // Created by 郭志贺 on 2020/5/27. 6 // Copyright © 2020 郭志贺. All rights reserved. 7 // 8 9 #import <Foundation/Foundation.h> 10 11 NS_ASSUME_NONNULL_BEGIN 12 13 @interface gzhCache : NSObject 14 15 /// 计算缓存大小 16 +(float)filePath; 17 18 /// 清理缓存 19 +(void)clearCache; 20 @end 21 22 NS_ASSUME_NONNULL_END
1 // 2 // gzhCache.m 3 // cache 4 // 5 // Created by 郭志贺 on 2020/5/27. 6 // Copyright © 2020 郭志贺. All rights reserved. 7 // 8 9 #import "gzhCache.h" 10 11 @implementation gzhCache 12 // 显示缓存大小 13 + (float)filePath { 14 NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ]; 15 16 return [ self folderSizeAtPath :cachPath]; 17 } 18 //计算单个文件的大小 19 + (long long) fileSizeAtPath:( NSString *) filePath{ 20 NSFileManager * manager = [ NSFileManager defaultManager ]; 21 if ([manager fileExistsAtPath :filePath]){ 22 return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ]; 23 } 24 return 0 ; 25 } 26 //遍历文件夹获得文件夹大小,返回多少M 27 + (float)folderSizeAtPath:(NSString *)folderPath{ 28 NSFileManager * manager = [ NSFileManager defaultManager ]; 29 if (![manager fileExistsAtPath :folderPath]) return 0 ; 30 NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath :folderPath] objectEnumerator ]; 31 NSString * fileName; 32 long long folderSize = 0 ; 33 while ((fileName = [childFilesEnumerator nextObject ]) != nil ){ 34 NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent :fileName]; 35 folderSize += [ self fileSizeAtPath :fileAbsolutePath]; 36 } 37 return folderSize/( 1024.0 * 1024.0 ); 38 } 39 //清理缓存 40 + (void)clearCache { 41 NSString * cachPath = [ NSSearchPathForDirectoriesInDomains ( NSCachesDirectory , NSUserDomainMask , YES ) firstObject ]; 42 NSArray * files = [[ NSFileManager defaultManager ] subpathsAtPath :cachPath]; 43 NSLog ( @"cachpath = %@" , cachPath); 44 for ( NSString * p in files) { 45 NSError * error = nil ; 46 NSString * path = [cachPath stringByAppendingPathComponent :p]; 47 if ([[ NSFileManager defaultManager ] fileExistsAtPath :path]) { 48 [[ NSFileManager defaultManager ] removeItemAtPath :path error :&error]; 49 } 50 } 51 [ self performSelectorOnMainThread : @selector (clearCachSuccess) withObject : nil waitUntilDone : YES ]; 52 } 53 + (void)clearCachSuccess { 54 NSLog(@"清理成功"); 55 } 56 @end
需要查询大小的地方使用:
NSString *str = [NSString stringWithFormat:@"%.2fM",[gzhCache filePath]];
清理的方法调用
[gzhCache clearCache];
以上内容仅代表本菜鸟看法,复制可直接使用。如有不妥之处敬请告知。
内容来源于网络如有侵权请私信删除
文章来源: 博客园
- 还没有人评论,欢迎说说您的想法!