简体   繁体   English

iOS - 获取目录中的文件大小

[英]iOS - Get sum of filesize in directory

I have the following code I use to cache photos I load off Flickr in the device's memory: 我有以下用于缓存照片的代码我在设备的内存中加载了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];
}

I want to limit this to 10MB and then if the limit is reached to remove the oldest photo in the cache, how can I get the total size of all the files I've saved and check which one is the oldest? 我想将此限制为10MB,然后如果达到限制以删除缓存中最旧的照片,我如何获得我保存的所有文件的总大小并检查哪一个是最早的?

You can get the size of a file like so 您可以像这样获得文件的大小

NSError *attributesError = nil;

    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError];

    int fileSize = [fileAttributes fileSize];

So you can maybe iterate through all the files in the folder and add up the file sizes...not sure if theres a direct way to get the directory size, also theres this SO post talking about this aswell, you can find a solution here 所以你可以遍历文件夹中的所有文件并添加文件大小...不确定是否直接获取目录大小,这也是这个SO帖子谈论这个,你可以在这里找到一个解决方案

To find the creation date of the file you can do 要查找文件的创建日期,您可以执行此操作

NSString *path = @"";
    NSDictionary* fileAttribs = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
    NSDate *result = [fileAttribs valueForKey:NSFileCreationDate]; //or NSFileModificationDate

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM