按创builddatesorting文件 – iOS

我试图获取我的目录中的所有文件,并根据创builddate或修改date进行sorting。 那里有很多例子,但是我不能让他们中的任何一个去工作。

任何人都有一个很好的例子,如何从datesorting的目录中获取文件的数组?

这里有两个步骤,获取具有创builddate的文件列表,并对它们进行sorting。

为了便于稍后对它们进行sorting,我创build了一个对象来保存其修改date的path:

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

现在,要获取文件和文件夹列表(不是深度search),使用这个:

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

请注意,一旦我创build了一个PathWithDate对象的数组,我使用sortUsingComparator把它们按正确的顺序(我select降序)。 为了使用创builddate,而不是使用[attr objectForKey:NSFileCreationDate]

Interesting Posts