【发布时间】:2012-07-25 05:24:58
【问题描述】:
我在应用程序的 Document 文件夹中有一个图像列表。我想按创建日期的顺序加载图像。 我该怎么做?
【问题讨论】:
标签: objective-c ios nsfilemanager
我在应用程序的 Document 文件夹中有一个图像列表。我想按创建日期的顺序加载图像。 我该怎么做?
【问题讨论】:
标签: objective-c ios nsfilemanager
我会看看:Getting a list of files in a directory with a glob
特别是 NSFileManager。您可以查看文件的属性。从那里您很可能可以使用 NSPredicate 进行排序。
【讨论】:
此代码将按创建顺序枚举您的文档目录中的所有文件:
查看代码中的 cmets 以了解发生了什么。
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);
}
【讨论】: