如何使用 NSURL 查看某个文件夹是否是另一个文件夹的子文件夹?

Sup*_*tar 4 cocoa nsurl swift

我有一个[URL]代表一组特殊父目录的目录。我得到了另一个[URL]代表分散在系统各处的文件。我想知道这些文件是否位于我的任何特殊目录或其任何子目录中。有没有一种简单/有意的方法可以做到这一点,而无需手动解析/遍历绝对 URL 的路径?

rma*_*ddy 6

没有任何方法NSURL可以让您查看另一个是否NSURL代表另一个的根路径。

一种可能的解决方案是使用 属性将两个 URL 转换为路径字符串path。然后查看一个字符串是否是另一个字符串的前缀。但在获取 URL 的路径之前,请同时使用URLByStandardizingPathURLByResolvingSymlinksInPath来确保结果一致。

例子:

NSURL *specialURL = ... // a URL for one of the special parent directories
NSURL *fileURL = ... // a URL for one of the files to check
NSString *specialPath = [specialURL.URLByStandardizingPath.URLByResolvingSymlinksInPath.path stringByAppendingString:@"/"];
NSString *filePath = fileURL.URLByStandardizingPath.URLByResolvingSymlinksInPath.path
if ([filePath hasPrefix:specialPath]) {
    // This file is in this special directory
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要在前缀测试之前向 `specialPath` 添加尾部斜杠,否则像 `/super` 这样的内容将被视为 `/supermarket/qfc` 的父级。(`NSURL` 的 `path` 属性会去除任何尾随的 `/`。) (3认同)