Sort files by creation date - iOS

2020-06-17 06:13发布

问题:

I´m trying to get all the files in i directory and sort them according to creation date or modify date. There are plenty of examples out there but I can´t get no one of them to work.

Anyone have a good example how to get an array of files from a directory sorted by date?

回答1:

There are two steps here, getting the list of files with their creation dates, and sorting them.

In order to make it easy to sort them later, I create an object to hold the path with its modification date:

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

@implementation PathWithModDate
@end

Now, to get the list of files and folders (not a deep search), use this:

- (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;
}

Note that once I create an array of PathWithDate objects, I use sortUsingComparator to put them in the right order (I chose descending). In order to use creation date instead, use [attr objectForKey:NSFileCreationDate] instead.