Jas*_*ien 26 iphone macos cocoa cocoa-touch nsstring
我一直在修改一些代码,以便在Mac OS X和iPhone OS之间工作.
我遇到了一些使用NSURL's URLByAppendingPathComponent:(在10.6中添加)的代码,有些人可能知道,这些代码在iPhone SDK中不可用.
我的解决方案是在OS之间使用这个代码
NSString *urlString = [myURL absoluteString];
urlString = [urlString stringByAppendingPathComponent:@"helloworld"];
myURL = [NSURL urlWithString:urlString];
Run Code Online (Sandbox Code Playgroud)
这样做的问题是NSString的stringByAppendingPathComponent:,似乎除去的/一个人从HTTP S:URL的一部分//.
这是预期的行为还是错误?
好的,所以我有点太快问上面的问题了.我重新阅读文档,它确实说:
请注意,此方法仅适用于文件路径(例如,不是URL的字符串表示)
但是,如果您需要将路径组件附加到iPhone上的URL,它不会为正确的方向提供任何指示...
我总是可以手动执行,添加/如果需要和额外的字符串,但我希望尽可能接近原始Mac OS X代码...
Chu*_*uck 15
我会myURLByAppendingPathComponent:在NSURL上实现一个做同样事情的方法.给它一个不同名称的原因是它不会覆盖Apple提供的方法,当Apple开始将10.6 API移植到iPhone时(所以"我的"只是一个例子 - 重点是它不太可能有人否则会写一个具有该名称的方法).
在我看来,你只是想弄乱路径而不是整个URL.这是一个未经测试的例子:
- (NSURL *)myURLByAppendingPathComponent:(NSString *)component {
NSString *newPath = [[self path] stringByAppendingPathComponent:component];
return [[[NSURL alloc] initWithScheme: [self scheme]
host: [self host]
path: newPath]
autorelease];
}
Run Code Online (Sandbox Code Playgroud)
它只适用于具有类文件路径的URL,但我很确定Apple方法的工作方式相同.无论如何,希望它可以帮助您朝着正确的方向前进.
nsc*_*hum 12
从iOS 4开始,URLByAppendingPathComponent可在iOS上使用并正确处理两个斜杠.(OS X从10.6开始就有了它,正如Chuck指出的那样)
myURL = [myURL URLByAppendingPathComponent:@"hello world"]
// http://foo/bar/hello%20world
Run Code Online (Sandbox Code Playgroud)
请注意,与stringByAppendingPathComponent此方法不同,此方法可以解除参数.
或者,有URLWithString:relativeToURL:,不逃避.因此,如果url组件已经转义,请使用:
myURL = [NSURL URLWithString:@"hello%20world" relativeToURL:myURL]
// http://foo/bar/hello%20world
Run Code Online (Sandbox Code Playgroud)
请注意,myURL需要在此处以斜杠结尾,并且添加的段不得包含前导斜杠.
该NSString的参考说这约stringByAppendingPathComponent:
请注意,此方法仅适用于文件路径(例如,URL的字符串表示形式)。
因此,我认为这是“不要这样做”的情况。
用-stringByAppendingString:代替吗?