[英]iOS - Get sum of filesize in directory
我有以下用於緩存照片的代碼我在設備的內存中加載了Flickr:
NSURL *urlForPhoto = [FlickrFetcher urlForPhoto:self.photo format:FlickrPhotoFormatLarge];
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [rootPath stringByAppendingString:[self.photo objectForKey:FLICKR_PHOTO_ID]];
NSData *dataForPhoto;
NSError *error = nil;
if ([[NSFileManager defaultManager] fileExistsAtPath:imagePath]) {
dataForPhoto = [NSData dataWithContentsOfFile:imagePath];
} else {
dataForPhoto = [NSData dataWithContentsOfURL:urlForPhoto];
[dataForPhoto writeToFile:imagePath atomically:YES];
}
我想將此限制為10MB,然后如果達到限制以刪除緩存中最舊的照片,我如何獲得我保存的所有文件的總大小並檢查哪一個是最早的?
您可以像這樣獲得文件的大小
NSError *attributesError = nil;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];
int fileSize = [fileAttributes fileSize];
所以你可以遍歷文件夾中的所有文件並添加文件大小...不確定是否直接獲取目錄大小,這也是這個SO帖子談論這個,你可以在這里找到一個解決方案
要查找文件的創建日期,您可以執行此操作
NSString *path = @"";
NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
NSDate *result = [fileAttribs valueForKey:NSFileCreationDate]; //or NSFileModificationDate
希望能幫助到你
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.