IOS - 按顺序加载本地文件

hoa*_*gpx 3 objective-c nsfilemanager ios

我在app的Document文件夹中有一个图像列表.我想按照创建日期的顺序加载图像.我怎样才能做到这一点 ?

das*_*ght 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);
}
Run Code Online (Sandbox Code Playgroud)