Sort files by creation date - iOS

可紊 提交于 2019-12-05 00:11:37

问题


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.



来源:https://stackoverflow.com/questions/7977664/sort-files-by-creation-date-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!