gpt4 book ai didi

NSURL 路径与绝对字符串

转载 作者:行者123 更新时间:2023-11-30 13:43:29 28 4
gpt4 key购买 nike

我在 SO 上看到了很多关于 NSURLNSString 之间转换的问题。它们都涉及使用 NSString *path = [myURL AbsoluteString];NSString *path = [myURL path];这些方法之间的实际区别是什么? 是否某个时候应该使用其中一种而不是另一种?我尝试查阅Apple Docs ,但我发现它没什么帮助。

我习惯于仅在有关网站和其他有关在不同计算机之间发送信息的主题的讨论中提及 URL,而在仅处理单台计算机上的文件结构时从未提及 URL。也许这就是我的一些困惑的来源,因为 NSURL 似乎是访问文件的首选方式,无论该文件是否存在于网络上或本地设备上。或者也许这是一个完全不相关的话题。我什至不确定。

最佳答案

问题 1:

What is the actual difference between these methods?

让我们分析一下这 6 行代码 - 3 行用于本地,3 行用于 http URL - 并稍微尝试一下它们。

让我们使用 file:// 方案创建一个 NSURL。如果您问自己为什么在 file: 之后有 3 个 /,您应该记住一个方案存在完整的 URL(file:// 和绝对或相对路径(您可以在 RFC 1808 on page 3 中找到有关创建 URL 的更多信息)。我们使用以 / 开头的绝对路径,以便我们以 ///.

NSURL *aLocalURL = [NSURL URLWithString:@"file:///Users/dennis/Desktop/"];
NSLog(@"absolute string: %@", aLocalURL.absoluteString);
NSLog(@"path: %@", aLocalURL.path);

输出:

absolute string: file:///Users/dennis/Desktop/
path: /Users/dennis/Desktop

因此我们看到 absoluteString 仍然知道其方案,而 path 不再拥有此信息。

注意: path 是一个文件(目录)URL,如 docs状态,尾部斜杠被删除。

<小时/>

现在让我们看一下远程 URL。大多数人都比较熟悉这些类型的 URL。我们使用与本地 URL 相同的过程来创建它。我们的方案现在是 http://,我们的 pathwww.apple.com/

NSURL *anHTTPURL = [NSURL URLWithString:@"http://www.apple.com/"];  
NSLog(@"absolute string: %@", anHTTPURL.absoluteString);
NSLog(@"path: %@", anHTTPURL.path);

输出:

absolute string: http://www.apple.com/
path: /

我们再次看到绝对字符串仍然知道其方案,但 path 现在是 /。因此,在使用远程 URL 时,path 似乎不是一种合适的方式。

但是,当我们有像 http://www.apple.com/index.html 这样的 URL 时,我们会得到

absolute string: http://www.apple.com/index.html
path: /index.html

阅读文档也有帮助:

Per RFC 3986, the leading slash after the authority (host name and port) portion is treated as part of the path.

因此,path 是从 authority 之后的斜杠开始(包括)的所有内容,在我们的例子中是 www.apple.com .

<小时/>

问题 2

Is there a time when one should be used over the other?

来自docs :(方法:路径)

If this URL object contains a file URL (as determined with isFileURL), the return value of this method is suitable for input into methods of NSFileManager or NSPathUtilities.

在我看来,这句话清楚表明,当您使用 NSFileManagerNSPathUtilities 时,应该使用 path .

<小时/>

结论:

当您使用远程 URL 时,您(通常)使用 absoluteString,否则结果不是您(通常)想要的。
当您使用本地 URL 时,请使用路径

来源:
http://www.ietf.org/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc3986.txt
NSURL Class Reference

关于NSURL 路径与绝对字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280105/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com