【问题标题】:Sorting a file path tree like Finder's Sort-by-Kind像 Finder 的 Sort-by-Kind 一样对文件路径树进行排序
【发布时间】:2016-02-12 13:35:55
【问题描述】:

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

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

/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 排序时:

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

【问题讨论】:

  • 手动递归目录,按路径组件计数和字母顺序排序。没有花太多时间在这上面,我想我最好在自己做一个容易出错的实现之前先问一下..
  • 在这里提问之前最好先尝试一下,表明您已经尝试过尝试解决自己的问题。不幸的是,您的问题没有显示。
  • 发布了当前不完整的代码

标签: objective-c cocoa


【解决方案1】:

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

HTH

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 2012-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多