在 iOS 專案中,若需要顯示快取大小或計算沙盒目錄佔用空間,通常會使用 NSFileManager 搭配檔案屬性來統計。本文說明如何計算自訂目錄大小,以及如何整合 SDImageCache 的快取統計。
attributesOfItemAtPath:error: 可以用來取得單一檔案的大小,但若要計算整個目錄,就需要先取得目錄底下所有檔案路徑。可利用 subpathsAtPath: 取得相對路徑,再逐一拼接成完整路徑。
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *subFiles = [fm subpathsAtPath:cachePath];
NSUInteger fileSize = 0;
for (NSString *fileName in subFiles) {
NSString *fullPath = [cachePath stringByAppendingPathComponent:fileName];
NSDictionary *attributes = [fm attributesOfItemAtPath:fullPath error:nil];
fileSize += [attributes fileSize];
}
若專案使用 SDWebImage,可透過 SDImageCache 提供的 calculateSizeWithCompletionBlock: 取得快取總大小。由於該方法常用於非同步情境,若需要同步取得結果,可搭配其內部使用的序列佇列。
SDImageCache *imageCache = [[SDWebImageManager sharedManager] imageCache];
dispatch_queue_t queue = imageCache.ioQueue;
[imageCache calculateSizeWithCompletionBlock:^(NSUInteger fileCount, NSUInteger totalSize) {
fileSize += totalSize;
}];
dispatch_sync(queue, ^{
NSArray *subFiles = [fm subpathsAtPath:cachePath];
for (NSString *fileName in subFiles) {
NSString *fullPath = [cachePath stringByAppendingPathComponent:fileName];
NSDictionary *attributes = [fm attributesOfItemAtPath:fullPath error:nil];
fileSize += [attributes fileSize];
}
});
使用 dispatch_sync 時,必須確認不會造成主線程死鎖。若 SDImageCache 的佇列為序列佇列,通常可以確保計算任務完成後再回傳結果。實際效能仍建議依專案資料量進行測試。