gpt4 book ai didi

objective-c - 像 Finder 的按种类排序一样对文件路径树进行排序

转载 作者:行者123 更新时间:2023-12-03 17:19:48 25 4
gpt4 key购买 nike

我正在尝试以深度优先的方式按字母顺序展平文件路径树。它应该将较浅的路径放在前面,并在各个目录中按字母顺序排序。

我想要的结果应该是这样的:

/a.data
/b.data
/x.data
/a/a/e.data
/a/a/f.data
/a/b/c/d.data
/a/c/d.data
/b/x.data

本质上:

file vs file - sort alphabetically
file vs directory - file first
directory vs directory - shallow first, otherwise alphabetically

在我自己花太多时间搞乱这件事并可能犯错误之前 - 有一个 Cocoa API 可以做到这一点吗?或者也许只是一个标准算法来实现这一点?

我目前正在做这样的事情:

// flatList is an unsorted array containing dictionaries
// which have file paths in the kBulkFilepathKey key.
// flatList has been populated earlier by enumerating a list of
// files and directories, and recursing on the directories.

[flatList sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {

NSDictionary *d1 = obj1;
NSDictionary *d2 = obj2;

// path1, path2 are full paths:
NSString *path1 = d1[kBulkFilepathKey];
NSString *path2 = d2[kBulkFilepathKey];

if(path2.pathComponents.count > path1.pathComponents.count)
return NSOrderedAscending;
else if (path1.pathComponents.count > path2.pathComponents.count)
return NSOrderedDescending;

return [path1 caseInsensitiveCompare:path2];
}];

还没有真正发挥作用。

谢谢!

编辑:刚刚意识到 - 我正在寻找与 OS X Finder 完全相同的行为,按 Kind 排序时:

file structure

但显然没有可用的 Cocoa API - 有 localizedStandardCompare:在 NSString 上,但这只是按字母顺序排序。

最佳答案

一旦确定两条路径具有相同数量的组件,您只需逐对比较两条路径中的组件 - 您就拥有了多键排序。如果一对组件不同,您就会得到总体答案,就像组件计数一样。如果一对相等,则移动到下一对。一个简单的循环就可以完成。

HTH

关于objective-c - 像 Finder 的按种类排序一样对文件路径树进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35363998/

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