Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort files by creation date - iOS

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?

like image 547
user974332 Avatar asked Nov 02 '11 08:11

user974332


People also ask

How do I change order of files in iOS?

Change how files and folders are sortedFrom an open location or folder, drag down from the center of the screen. Tap “Sorted by,” then choose an option: Name, Date, Size, Kind, or Tags.

How do I sort files by Date on Mac?

Sort items: In any view, choose View > Show View Options, click the Sort By pop-up menu, then choose the sort order, such as Date Modified or Name. In List view, move the pointer over the column name you want to sort by, then click it.


1 Answers

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.

like image 97
stevel Avatar answered Sep 23 '22 14:09

stevel