如何解决iOS 中的文件是否按添加日期自动排序?
我想知道我是否使用 FileManager 将一堆文件添加到 Documents 目录中,并在稍后检索它们,它们是否已经按“添加日期”顺序排列?即,最旧的将在数组中排在第一位,最新的将在数组中排在最后。
我之所以这么问是因为在模拟器中,如果我先执行 <div id="indexContainer" >
<p style="font-size:40px; color:#9b9da0;">Select a server</p>
<input type="button" value="Add" id="addBtnIcon" onclick="addBtnChange();">
<input type="button" value="Edit" id="editBtn" onclick="editBtnClick();">
<input type="button" value="Remove" id="removeBtn" style="padding:20px 20px; " onclick="removeBtnClick()"><br>
<form>
<p id="serverName" value="Server name here"></p>
<p id="serverValue" value="Server address here"></p><br>
<input type="submit" id="saveBtn" value="Save" style="background-color:#9b9da0; padding:20px 140px;" disabled><br>
</form>
<div class="description">
<p id="serverDesc">Description: A description goes here</p>
<p id="serverSerial">Serial no: The serial number goes here</p>
</div>
</div>
然后执行 fm.createFile(atPath: ".../Documents/hello1.txt",contents: someData,attributes: nil)
并检索它们,它们会按顺序显示(hello1 先然后 hello2)。我想知道这种行为是否会始终保持一致。如果是,那么我可以执行 fm.createFile(atPath: ".../Documents/hello2.txt",attributes: nil)
来获取我目录中最旧的文件。
请告诉我此行为在实际 iOS 设备上是否一致。
提前致谢。
解决方法
它们是否已经按“添加日期”顺序排列?
没有。如果 contentsOfDirectory
有任何顺序,它基本上只是按字母顺序排列。按年龄排序完全取决于您。
在您的示例中,年龄顺序和返回的顺序相同,这纯属巧合。
,简短的回答是否定的。在运行时不能保证顺序。您必须自己对数组进行排序。我建议尝试这样的事情。
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
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。