【问题标题】:Are files in iOS automatically sorted by date added?iOS中的文件是否自动按添加日期排序?
【发布时间】:2021-10-02 14:10:15
【问题描述】:

我想知道我是否使用 FileManager 将一堆文件添加到 Documents 目录中,然后在稍后检索它们,它们是否已经按“添加日期”顺序排列?即,最旧的将在数组中排在第一位,而最新的将在数组中排在最后。

我问这个是因为在模拟器中如果我执行fm.createFile(atPath: ".../Documents/hello1.txt", contents: someData, attributes: nil) 然后执行fm.createFile(atPath: ".../Documents/hello2.txt", contents: someData, attributes: nil) 并检索它们,它们会按顺序显示(hello1 首先然后是 hello2)。我想知道这种行为是否会始终保持一致。如果是,那么我可以通过 fm.contentsOfDirectory(atPath: .../Documents).first! 获取目录中最旧的文件。

如果此行为在实际 iOS 设备上保持一致,请告诉我。

提前致谢。

【问题讨论】:

    标签: ios swift nsfilemanager


    【解决方案1】:

    简短的回答是否定的。在运行时无法保证订单。您必须自己对数组进行排序。我建议改用这样的方法。

        let orderedURLs = try? FileManager.default.contentsOfDirectory(at: myDirectoryUrl, includingPropertiesForKeys: [.creationDateKey], options: .skipsHiddenFiles).sorted(by: {
            if let date1 = try? $0.resourceValues(forKeys: [.creationDateKey]).creationDate,
               let date2 = try? $1.resourceValues(forKeys: [.creationDateKey]).creationDate {
                return date1 < date2
            }
            return false
        })
    

    【讨论】:

      【解决方案2】:

      它们是否已经按“添加日期”顺序排列?

      没有。 contentsOfDirectory 基本上只是按字母顺序排列,如果它有任何顺序的话。按年龄排序完全取决于您。

      在您的示例中,年龄顺序和退货顺序相同纯属巧合。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-16
      • 2011-12-20
      • 2019-07-25
      • 1970-01-01
      • 2019-04-21
      • 2017-04-23
      • 2013-05-02
      相关资源
      最近更新 更多