Sort files by creation date - iOS

I try to get all the files in the directory i and sort them according to the creation date or the date of change. There are many examples, but I cannot work any of them.

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

+6
source share
1 answer

There are two steps here: getting a list of files with creation dates and sorting them.

To simplify sorting later, I create an object to store the path with the date it was changed:

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

Now, to get a list of files and folders (rather than 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; } 

Please note that as soon as I create an array of PathWithDate objects, I use sortUsingComparator to place them in the correct order (I selected descending). To use the creation date instead, use [attr objectForKey:NSFileCreationDate] .

+5
source

Source: https://habr.com/ru/post/900588/


All Articles