是否有理由在(URL).hasDirectoryPath上使用(FileManager)fileExistsAtPath:isDirectory :?

mre*_*dig 0 objective-c swift

(FileManager)fileExistsAtPath:isDirectory:(URL).hasDirectoryPath之间的实际区别是什么?

我正在关注一些教程,他们首先使用FileManager方法,但随后似乎始终使用URL方法。在我看来,URL方法似乎更简洁,更容易记住。是否有任何理由改用FileManager方法?(如果答案是肯定的,请提供示例)

Cha*_*tka 5

与接受的答案相反,区别不仅在于可用性。该FileManagerAPI实际上访问URL磁盘上由指向的文件,以查看它是否是目录,hasDirectoryPath但不是。它仅检查URL路径/的末尾是否带有斜杠(),这表明该路径指向目录。您可以通过制作一个应用程序并在“文件活动”工具中运行它来验证这一点。与FileManager您将lstat64在目录上看到一个,而与hasDirectoryPath您将不会。

这有一些影响:

  1. hasDirectoryPath 显然,由于它不访问磁盘,因此执行速度会快得多。

  2. 但是,hasDirectoryPath如果URL有关尾随斜杠的存在,的路径不正确,则可能会给出错误的结果。例如:

    URL(string: "file:///usr/bin")!.hasDirectoryPath // evaluates to false URL(string: "file:///usr/bin/")!.hasDirectoryPath // evaluates to true

  3. 最后,hasDirectoryPath可以在非上工作file: URL,例如http: URL,而FileManager显然不能。

综上所述,当您需要通过文件系统进行检查时,最好使用URL基于-的机制而不是基于路径的机制FileManager

let isDir = (try? self.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false
Run Code Online (Sandbox Code Playgroud)