2020-05-27

iOS开发一行代码搞定缓存计算及清除缓存

iOS开发一行代码搞定缓存计算及清除缓存


话不多说,直接撸代码

 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_BEGIN12 13 @interface gzhCache : NSObject14 15 /// 计算缓存大小16 +(float)filePath;17 18 /// 清理缓存19 +(void)clearCache;20 @end21 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 gzhCache12 // 显示缓存大小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 //遍历文件夹获得文件夹大小,返回多少M27 + (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];

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


No comments:

Post a Comment