【问题标题】:Finder algorithm for "sort by name" options“按名称排序”选项的 Finder 算法
【发布时间】:2021-03-01 03:32:09
【问题描述】:

我使用NSFileManager 类来创建URL 的集合

let resourceKeys = Set<URLResourceKey>([.nameKey, .isDirectoryKey, .typeIdentifierKey])

let directoryContents = try FileManager.default.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: Array(resourceKeys), options: .skipsHiddenFiles)
let fileURLs = directoryContents.filter { (url) -> Bool in
    do {
        let resourceValues = try url.resourceValues(forKeys: resourceKeys)
        return !resourceValues.isDirectory! && resourceValues.typeIdentifier! == "public.jpeg"
    } catch { return false }
}

下一步我按文件名对fileURLs集合进行排序

let sortedFileURLs = fileURLs.sorted(by: { (URL1: URL, URL2: URL) -> Bool in
    return URL1.pathComponents.last! < URL2.pathComponents.last!
})

它有效,但它不是 Finder 用于“按名称排序”选项的方式(另一个排序结果) 请帮忙!什么算法使用 Finder 进行“按名称排序”

【问题讨论】:

    标签: swift sorting url nsfilemanager finder


    【解决方案1】:

    类似Finder的排序顺序可以用localizedStandardCompare实现

    文档说:

    只要文件名或其他字符串出现在适合 Finder 式排序的列表和表格中,就应该使用此方法。

    let sortedFileURLs = fileURLs.sorted{ $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending }
    

    注意:lastPathComponent 优于 pathComponents.last!

    【讨论】:

    • 非常感谢!
    • 而不是排序最后一个路径组件更好地使用 URLResourceKey 本地化NameKey 排序。 lastPathComponent 将始终返回“图片”,而localizedNameKey 将返回类似“fotos”(葡萄牙语)的等价物。 OP 在向用户显示文件名时也应该使用localizedName
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多