您好,登錄后才能下訂單哦!
這篇文章主要為大家展示了iOS開(kāi)發(fā)之如何實(shí)現(xiàn)緩存計(jì)算及清除緩存,內(nèi)容簡(jiǎn)而易懂,希望大家可以學(xué)習(xí)一下,學(xué)習(xí)完之后肯定會(huì)有收獲的,下面讓小編帶大家一起來(lái)看看吧。
話不多說(shuō),直接擼代碼
// // 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 /// 計(jì)算緩存大小 +(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]; } //計(jì)算單個(gè)文件的大小 + (long long) fileSizeAtPath:( NSString *) filePath{ NSFileManager * manager = [ NSFileManager defaultManager ]; if ([manager fileExistsAtPath :filePath]){ return [[manager attributesOfItemAtPath :filePath error : nil ] fileSize ]; } return 0 ; } //遍歷文件夾獲得文件夾大小,返回多少M(fèi) + (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]];
清理的方法調(diào)用
[gzhCache clearCache];
以上就是關(guān)于iOS開(kāi)發(fā)之如何實(shí)現(xiàn)緩存計(jì)算及清除緩存的內(nèi)容,如果你們有學(xué)習(xí)到知識(shí)或者技能,可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。