ios - 如何按名称对 nsdocumentdirectory 中的文件进行排序?

标签 ios objective-c xcode

我在 nsdocumentdirectory 中有一些文件,当我获取这些文件时,它会返回随机位置的文件。我正在使用以下代码:

NSString *downloadDirectory = [Utility bookDownloadFolder];
NSString *bookFolder = [[_selectedBook.zipFile lastPathComponent] stringByDeletingPathExtension];
NSString *bookFolderFinal = [downloadDirectory stringByAppendingPathComponent:bookFolder];
NSMutableArray *retval = [NSMutableArray array];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSArray *files = [fileManager contentsOfDirectoryAtPath:bookFolderFinal error:&error];

输出是这样的:

文件("1.jpg","1.txt","10.jpg","10.txt""11.jpg","11.txt","12.jpg","12.txt ","13.jpg","13.txt","2.jpg","2.txt", "3.jpg","3.txt","4.jpg","4.txt", "5.jpg","5.txt","6.jpg","6.txt""7.jpg","7.txt", "__MACOSX" )

但我希望输出按升序排列,例如:files("1.jpg","1.txt","2.jpg","2.txt",)

如果我使用 localizedCaseInsensitiveCompare 对数组进行排序,在这种情况下它不起作用,如果我使用 localizedCaseInsensitiveCompare 那么输出只是这样的。(“__MACOSX”,“1.jpg”,“1.txt”,“10.jpg", "10.txt", "11.jpg", "11.txt", "12.jpg", "12.txt", "13.jpg", "13.txt", "2. jpg", "2.txt", "3.jpg", "3.txt", "4.jpg", "4.txt", "5.jpg", )

最佳答案

为 Swift 4 扩展和更新 Oleg 的答案:

contentsOfDirectory(at:) 的文档声明返回的 URL 的顺序是“未定义的”。我不确定很多开发人员是否期望如此,但无论如何......

第一项工作是获取文件 URL:

let maybeURLs = try? FileManager.default.contentsOfDirectory(
        at: rootURL,
        includingPropertiesForKeys: [.isDirectoryKey],
        options: [.skipsSubdirectoryDescendants, .skipsHiddenFiles])

guard let urls = maybeURLs else { return }

现在我们必须像 Finder 那样对 URL 进行排序。

在这种情况下,因为我们知道所有文件都属于同一个目录,所以我们可以仅使用 lastPathComponent(幸运的是,它是一个字符串。)进行比较

您可以扩展比较逻辑以忽略后缀(.txt 与 .jpg)等

let sortedURLs = urls.sorted { a, b in
    return a.lastPathComponent
        .localizedStandardCompare(b.lastPathComponent)
            == ComparisonResult.orderedAscending
}

打印结果:

sortedURLs.forEach { print($0.lastPathComponent) }

1 Foo.txt
10 Bar.txt
100 Baz.txt
200 Boo.txt
210 Moo.txt

关于ios - 如何按名称对 nsdocumentdirectory 中的文件进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38527457/

相关文章:

objective-c - 将 Storyboard中的 UIViewController 更改为 UITableViewController?

iphone - iPhone 迄今为止最好的 JSON 解析器

ios - 应用程序扩展中的内存泄漏,UIAlertAction 附加到 UiViewController

xcode - 在 XCode 中启用代码 View 的抗锯齿

ios - 将 NSAttributedString 转换为 HTML 字符串

ios - 无法为自定义栏按钮设置标题?

ios - 使用滑动呈现/创建 View Controller

ios - 如何从 iOS 开始显示自定义菜单项?

ios - 如何检测iOS中的wifi网络变化

iphone - 如何在应用程序崩溃(或只是卡住)时显示错误消息?