iOS – 获取目录中文件大小的总和

我用下面的代码来caching照片,我装载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,然后如果达到删除caching中最老的照片的限制,我怎样才能得到我保存的所有文件的总大小,并检查哪一个是最古老的?

你可以像这样得到一个文件的大小

 NSError *attributesError = nil; NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:URL error:&attributesError]; int fileSize = [fileAttributes fileSize]; 

所以,你可以遍历文件夹中的所有文件,并添加文件大小…不知道如果直接的方式来获取目录的大小,也是这个SOpost谈论这也是,你可以在这里find一个解决scheme

要find文件的创builddate,你可以做

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

希望能帮助到你