標籤:suse attr contains manager 磁碟 判斷 執行 rect nsca
SDWebImage架構中在自動做磁碟緩衝的過程中,底層實現了計算Cache的大小,架構的方法名稱是getSize,但方法不容易被人理解,我就從新寫了一下,附帶注釋
基本思想: 1. 先取出的Cache,擷取該檔案的路徑
2. 利用NSFileManager,取出該檔案下的所有子路徑返回一個數組
3.遍曆數組,利用檔案的fileSize屬性,把每個子路徑下檔案的取出來累加,即為該檔案夾的大小
注意: 注意檔案夾的隱藏檔案,會使得到的檔案大小出現偏差
得到的大小為B,若是在蘋果手機中,需轉化M(需要除去(1000.0 * 1000.0))
// 擷取cache檔案夾路徑
NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
// 建立檔案管理者單粒(要想管理檔案,必須使用NSFileManager)
NSFileManager *mgr = [NSFileManager defaultManager];
// 擷取檔案夾所有子路徑數組:擷取多級目錄下檔案路徑
NSArray *subpaths = [mgr subpathsAtPath:cachePath];
// 遍曆
int totalSize = 0;
for (NSString *subPath in subpaths) {
//拼接每一條子路徑
NSString *filePath = [cachePath stringByAppendingPathComponent:subPath];
// 判斷是否是隱藏檔案(.DS為蘋果中的一種隱藏檔案),若是隱藏檔案,跳過該次執行,進入下次執行
if ([filePath containsString:@".DS"]) continue;
// 判斷是否是檔案夾
BOOL isDirectory = NO;
//如果檔案不存在或者為檔案夾,就跳過
BOOL isExists = [mgr fileExistsAtPath:filePath isDirectory:&isDirectory];
if (!isExists || isDirectory) continue;
// 擷取檔案屬性(利用檔案的fileSize屬性)
NSDictionary *attr = [mgr attributesOfItemAtPath:filePath error:nil];
totalSize += [attr fileSize];
iOS中計算磁碟快取檔案夾的大小