我在 iOS 应用程序和 Foundation 工具中尝试了以下行:
[@"http://www.apple.com/" stringByAppendingPathComponent:@"/"]
每次我得到的结果都是:
@"http:/www.apple.com"
换句话说,stringByAppendingPathComponent
除了不附加任何内容(这是我所期望的)之外,还吞下了最后一个/
(这可以认为是OK的), 和吞并了 URL 方案 /
之一,这在我看来是完全不行的。
只有我遇到这种情况吗?在提交错误报告之前我是否错过了一些愚蠢的事情?
最佳答案
首先,请注意 stringByAppendingPathComponent:
的文档:
Note that this method only works with file paths (not, for example, string representations of URLs).
因此,您正在使用该方法来处理它不支持的情况。
不过,将其与文件路径一起使用会显示相同的行为:
[@"/abc/" stringByAppendingPathComponent:@"/"]; // -> @"/abc"
[@"/abc/" stringByAppendingPathComponent:@"/def/"]; // -> @"/abc/def"
因此,该方法似乎总是更喜欢不以尾部斜杠结尾的路径,无论斜杠是原始路径还是参数的一部分。不过,我不知道我是否会称其为错误。毕竟,/abc
和 /abc/
都在文件系统上指定了相同的项目,不是吗?
但听起来确实可以更好地记录确切的行为。
关于cocoa - stringByAppendingPathComponent 中的基础错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5568633/