我在应用程序的 Document 文件夹中有一个图像列表。我想按创建日期的顺序加载图像。我怎样才能做到这一点 ?
问问题
1364 次
2 回答
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);
}
于 2012-07-26T15:38:48.690 回答
1
我会看一下:Getting a list of files in a directory with a glob
特别是 NSFileManager。您可以查看文件的属性。从那里您很可能可以使用 NSPredicate 进行排序。
于 2012-07-26T15:24:59.657 回答