在實現(xiàn)緩存的計算和清理之前说贝,我們要先知道緩存存在哪里了议惰。
應(yīng)用的沙盒主要有以下幾個目錄:
Document
:適合存儲重要的數(shù)據(jù), iTunes同步應(yīng)用時會同步該文件下的內(nèi)容
Library/Caches
:適合存儲體積大乡恕,不需要備份的非重要數(shù)據(jù)言询,iTunes不會同步該文件
Library/Preferences
:通常保存應(yīng)用的設(shè)置信息, iTunes會同步
tmp
:保存應(yīng)用的臨時文件,用完就刪除傲宜,系統(tǒng)可能在應(yīng)用沒在運行時刪除該目錄下的文件运杭,iTunes不會同步
由此知道,緩存一般是存儲在Library/Caches
這個路徑下蛋哭。
我們加載網(wǎng)絡(luò)圖片多數(shù)都使用的SDWebImage县习,SDWebImage提供了方法計算緩存和清理緩存:
// totalSize緩存大小
[[SDImageCache sharedImageCache] calculateSizeWithCompletionBlock:^(NSUInteger fileCount, NSUInteger totalSize) {
CGFloat mbSize = totalSize/1000/1000;
DEBUGLog(@"緩存 : %f",mbSize);
}];
//清理緩存
[[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
不過SDWebImage清理的是它緩存下來的圖片涮母,如果有其他緩存是沒有計算在內(nèi)的谆趾。
自己實現(xiàn)緩存計算和清理:
+ (NSInteger)getCacheSizeWithFilePath:(NSString *)path {
// 獲取“path”文件夾下的所有文件
NSArray *subPathArr = [[NSFileManager defaultManager] subpathsAtPath:path];
NSString *filePath = nil;
NSInteger totleSize = 0;
for (NSString *subPath in subPathArr) {
filePath = [path stringByAppendingPathComponent:subPath];
BOOL isDirectory = NO;
BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
//忽略不需要計算的文件:文件夾不存在/ 過濾文件夾/隱藏文件
if (!isExist || isDirectory || [filePath containsString:@".DS"]) {
continue;
}
/** attributesOfItemAtPath: 文件夾路徑 該方法只能獲取文件的屬性, 無法獲取文件夾屬性, 所以也是需要遍歷文件夾的每一個文件的原因 */
NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
NSInteger size = [dict[@"NSFileSize"] integerValue];
// 計算總大小
totleSize += size;
}
return totleSize;
}
//將文件大小轉(zhuǎn)換為 M/KB/B
+ (NSString *)fileSizeConversion:(NSInteger)totalSize {
NSString *totleStr = nil;
if (totalSize > 1000 * 1000) {
totleStr = [NSString stringWithFormat:@"%.2fM",totalSize / 1000.00f /1000.00f];
} else if (totalSize > 1000) {
totleStr = [NSString stringWithFormat:@"%.2fKB",totalSize / 1000.00f ];
} else {
totleStr = [NSString stringWithFormat:@"%.2fB",totalSize / 1.00f];
}
return totleStr;
}
//清除path文件夾下緩存
+ (BOOL)clearCacheWithFilePath:(NSString *)path {
//拿到path路徑的下一級目錄的子文件夾
NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
NSString *filePath = nil;
NSError *error = nil;
for (NSString *subPath in subPathArr) {
filePath = [path stringByAppendingPathComponent:subPath];
//刪除子文件夾
[[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
if (error) {
return NO;
}
}
return YES;
}
//緩存路徑
NSString *libraryCachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
調(diào)用方法getCacheSizeWithFilePath
,path傳上面的緩存路徑叛本,就可以計算出緩存大小沪蓬,調(diào)用clearCacheWithFilePath
清理緩存。