話不多說,直接擼代碼 1 // 2 // gzhCache.h 3 // cache 4 // 5 // Created by 郭志賀 on 2020/5/27. 6 // Copyright © 2020 郭志賀. All rights reserved. 7 // 8 9 #import <Fo ...
話不多說,直接擼代碼
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];
以上內容僅代表本菜鳥看法,複製可直接使用。如有不妥之處敬請告知。