[英]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.