我一直在修改一些代码以在 Mac OS X 和 iPhone OS 之间工作。
我遇到了一些使用 NSURL
的 URLByAppendingPathComponent:
(在 10.6 中添加)的代码,有些人可能知道,iPhone SDK 中不提供该代码.
让此代码在操作系统之间工作的解决方案是使用
NSString *urlString = [myURL absoluteString];
urlString = [urlString stringByAppendingPathComponent:@"helloworld"];
myURL = [NSURL urlWithString:urlString];
问题是 NSString
的 stringByAppendingPathComponent:
似乎从 URL 的 http://部分删除了一个/。
这是预期行为还是错误?
<小时/>编辑
好吧,所以我问上面的问题有点太快了。我重新阅读了文档,它确实说:
Note that this method only works with file paths (not, for example, string representations of URLs)
但是,如果您需要将路径组件附加到 iPhone 上的 URL,它不会提供任何正确方向的指示...
我总是可以手动执行此操作,添加/if 必要和额外的字符串,但我希望使其尽可能接近原始的 Mac OS X 代码...
最佳答案
我会在 NSURL 上实现一个 myURLByAppendingPathComponent:
方法来完成同样的事情。给它起一个不同的名称的原因是,当 Apple 将 10.6 API 移植到 iPhone 时,它不会覆盖 Apple 提供的方法(因此“my”只是一个例子 - 重点是它不太可能被其他人使用)否则会编写一个具有该名称的方法)。
在我看来,你只是想弄乱路径而不是整个 URL。这是一个未经测试的示例:
- (NSURL *)myURLByAppendingPathComponent:(NSString *)component {
NSString *newPath = [[self path] stringByAppendingPathComponent:component];
return [[[NSURL alloc] initWithScheme: [self scheme]
host: [self host]
path: newPath]
autorelease];
}
它只适用于具有类似文件路径的 URL,但我很确定 Apple 方法也能以相同的方式工作。无论如何,希望它能帮助您朝着正确的方向前进。
关于iphone - NSString 的 stringByAppendingPathComponent : removes a '/' in http://,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2579544/