iOS开发之1行代码实现缓存计算及清除缓存
作者:MrGuo还在搬砖
这篇文章主要给大家介绍了关于iOS开发之1行代码实现缓存计算及清除缓存的相关资料,文中通过示例代码介绍的非常详细,对各位iOS开发者们具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
话不多说,直接撸代码
// // 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
// // 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
需要查询大小的地方使用:
NSString *str = [NSString stringWithFormat:@"%.2fM",[gzhCache filePath]];
清理的方法调用
[gzhCache clearCache];
以上内容仅代表本菜鸟看法,复制可直接使用。如有不妥之处敬请告知。
好了,到此这篇iOS开发之1行代码实现缓存计算及清除缓存的文章就介绍到这了,更多相关iOS缓存计算及清除缓存内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!