簡體   English   中英

像Finder的按種類排序一樣對文件路徑樹進行排序

[英]Sorting a file path tree like Finder's Sort-by-Kind

我正在嘗試以深度優先的方式按字母順序拼合一棵文件路徑樹。 它應該將較淺的路徑放在首位,並在各個目錄中按字母順序排序。

我想要的結果應如下所示:

/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

在我花太多時間搞砸自己並可能出錯之前,請問有可可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];
}];

尚未真正起作用。

謝謝!

編輯:剛剛意識到-我在按Kind排序時正在尋找OS X Finder完全相同的行為:

文件結構

但是顯然沒有針對此的Cocoa API-NSString上有localizedStandardCompare :,但這只是字母順序。

一旦確定兩個路徑具有相同數量的組件,您只需要配對比較兩個路徑中的組件,就可以進行多鍵排序。 如果一對組件不同,您將獲得總體答案,就像組件數量一樣。 如果一對相等,則轉到下一對。 一個簡單的循環就可以做到。

HTH

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM