gpt4 book ai didi

objective-c - 按修改日期降序获取文件夹顺序中的文件列表

转载 作者:行者123 更新时间:2023-12-03 16:31:37 26 4
gpt4 key购买 nike

我需要获取按创建日期降序排序的数组中的文件列表,即最近修改的文件位于顶部。我使用 NSFileManager 检查了一些内置选项。有可用的开箱即用选项吗?

NSArray *filePathsArray =
[[NSFileManager defaultManager] subpathsOfDirectoryAtPath:documentsDirectory error:nil];

最佳答案

参见this ,也许会有帮助

//This is reusable method which takes folder path and returns sorted file list
-(NSArray*)getSortedFilesFromFolder: (NSString*)folderPath
{
NSError *error = nil;
NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF EndsWith '.pdf'"];//Take only pdf file
filesArray = [filesArray filteredArrayUsingPredicate:predicate];

// sort by creation date
NSMutableArray* filesAndProperties = [NSMutableArray arrayWithCapacity:[filesArray count]];

for(NSString* file in filesArray) {

if (![file isEqualToString:@".DS_Store"]) {
NSString* filePath = [folderPath stringByAppendingPathComponent:file];
NSDictionary* properties = [[NSFileManager defaultManager]
attributesOfItemAtPath:filePath
error:&error];
NSDate* modDate = [properties objectForKey:NSFileModificationDate];

[filesAndProperties addObject:[NSDictionary dictionaryWithObjectsAndKeys:
file, @"path",
modDate, @"lastModDate",
nil]];

}
}

// Sort using a block - order inverted as we want latest date first
NSArray* sortedFiles = [filesAndProperties sortedArrayUsingComparator:
^(id path1, id path2)
{
// compare
NSComparisonResult comp = [[path1 objectForKey:@"lastModDate"] compare:
[path2 objectForKey:@"lastModDate"]];
// invert ordering
if (comp == NSOrderedDescending) {
comp = NSOrderedAscending;
}
else if(comp == NSOrderedAscending){
comp = NSOrderedDescending;
}
return comp;
}];

return sortedFiles;

}

关于objective-c - 按修改日期降序获取文件夹顺序中的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22827607/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com