【问题标题】:Sort files by creation date - iOS按创建日期排序文件 - iOS
【发布时间】:2011-12-20 03:08:14
【问题描述】:

我正在尝试获取 i 目录中的所有文件并根据创建日期或修改日期对它们进行排序。那里有很多例子,但我无法让其中任何一个工作。

谁有一个很好的例子,如何从按日期排序的目录中获取文件数组?

【问题讨论】:

标签: objective-c ios file directory


【解决方案1】:

这里有两个步骤,获取文件列表及其创建日期,然后对它们进行排序。

为了方便以后对它们进行排序,我创建了一个对象来保存路径及其修改日期:

@interface PathWithModDate : NSObject
@property (strong) NSString *path;
@property (strong) NSDate *modDate;
@end

@implementation PathWithModDate
@end

现在,要获取文件和文件夹列表(不是深度搜索),请使用:

- (NSArray*)getFilesAtPathSortedByModificationDate:(NSString*)folderPath {
    NSArray *allPaths = [NSFileManager.defaultManager contentsOfDirectoryAtPath:folderPath error:nil];

    NSMutableArray *sortedPaths = [NSMutableArray new];
    for (NSString *path in allPaths) {
        NSString *fullPath = [folderPath stringByAppendingPathComponent:path];

        NSDictionary *attr = [NSFileManager.defaultManager attributesOfItemAtPath:fullPath error:nil];
        NSDate *modDate = [attr objectForKey:NSFileModificationDate];

        PathWithModDate *pathWithDate = [[PathWithModDate alloc] init];
        pathWithDate.path = fullPath;
        pathWithDate.modDate = modDate;
        [sortedPaths addObject:pathWithDate];
    }

    [sortedPaths sortUsingComparator:^(PathWithModDate *path1, PathWithModDate *path2) {
        // Descending (most recently modified first)
        return [path2.modDate compare:path1.modDate];
    }];

    return sortedPaths;
}

请注意,一旦我创建了一个 PathWithDate 对象数组,我就使用sortUsingComparator 将它们按正确的顺序排列(我选择了降序)。要改用创建日期,请改用[attr objectForKey:NSFileCreationDate]

【讨论】:

  • 您可以使用 NSDictionary 代替 PathWithModDate。不需要为此声明一个类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-12
  • 2017-03-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多