我在app的Document文件夹中有一个图像列表。我想按创建日期的顺序加载图像。 我怎么能这样做?
答案 0 :(得分:5)
此代码将按照创建顺序枚举文档目录中的所有文件:
请参阅代码中的注释以了解正在发生的事情。
NSFileManager *fm = [NSFileManager defaultManager];
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSError *err;
// Get all files with their creation date
NSArray *files = [fm contentsOfDirectoryAtURL:[[NSURL alloc] initFileURLWithPath:doc isDirectory:YES]
includingPropertiesForKeys:[NSArray arrayWithObject:NSURLCreationDateKey]
options:0
error:&err];
// Using file's URL as the key, store creation date as the value
NSMutableDictionary *urlWithDate = [NSMutableDictionary dictionaryWithCapacity:files.count];
for (NSURL *f in files) {
NSDate *creationDate;
if ([f getResourceValue:&creationDate forKey:NSURLCreationDateKey error:&err]) {
[urlWithDate setObject:creationDate forKey:f];
}
}
// Sort the dictionary on the value, which is the creation key
for (NSURL *f in [urlWithDate keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
return [obj1 compare:obj2];
}]) {
// Check if the file is an image. Load if it is an image, otherwise skip.
NSLog(@"%@", f);
}
答案 1 :(得分:1)
我想看看:Getting a list of files in a directory with a glob
特别是NSFileManager。您可以查看文件的属性。从那里你很可能使用NSPredicate进行排序。