我试图获取 i 目录中的所有文件并根据创建日期或修改日期对它们进行排序。那里有很多例子,但我无法让其中任何一个起作用。
有人有一个很好的例子如何从按日期排序的目录中获取文件数组吗?
这里有两个步骤,获取文件列表及其创建日期,并对它们进行排序。
为了便于以后对它们进行排序,我创建了一个对象来保存路径及其修改日期:
@interface PathWithModDate : NSObject
@property (strong) NSString *path;
@property (strong) NSDate *modDate;
@end
@implementation PathWithModDate
@end
现在,要获取文件和文件夹的列表(不是深度搜索),请使用以下命令:
- (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;
}
请注意,一旦我创建了 PathWithDate 对象的数组,我就会使用sortUsingComparator
将它们按正确的顺序排列(我选择降序)。为了使用创建日期,请使用[attr objectForKey:NSFileCreationDate]
反而。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)