Objective c -[NSString stringByAppendingPathComponent:]或仅-NSString stringByAppendingFormat:]用于NSRLS的NSStrings?

Objective c -[NSString stringByAppendingPathComponent:]或仅-NSString stringByAppendingFormat:]用于NSRLS的NSStrings?,objective-c,foundation,Objective C,Foundation,调用+[NSURL URLWithString:时,我有两个构建URL的选项: [[@"http://example.com" stringByAppendingPathComponent:@"foo"] stringByAppendingPathComponent:@"bar"] 或 -[NSString-stringByAppendingPathComponent:似乎是更正确的答案,但是使用-[NSString-stringByAppendingFormat:除了像下面这样处理双斜杠之外

调用
+[NSURL URLWithString:
时,我有两个构建URL的选项:

[[@"http://example.com" stringByAppendingPathComponent:@"foo"] stringByAppendingPathComponent:@"bar"]

-[NSString-stringByAppendingPathComponent:
似乎是更正确的答案,但是使用
-[NSString-stringByAppendingFormat:
除了像下面这样处理双斜杠之外,我还会丢失任何东西吗

// http://example.com/foo/bar
[[@"http://example.com/" stringByAppendingPathComponent:@"/foo"] stringByAppendingPathComponent:@"bar"] 

// http://example.com//foo/bar  oops!
[@"http://example.com/" stringByAppendingFormat:@"/%@/%@",@"foo",@"bar"];

stringByAppendingPathComponent的要点是处理双斜杠,但是,您可以执行以下操作:

[[@"http://example.com/" stringByAppendingPathComponent:[NSString stringWithFormat:@"%@/%@", @"foo", @"bar"]]
那么:

[NSString pathWithComponents:@[@]http://example.com“,@“foo”,@“bar”]]

正如评论中所指出的,当使用
nspathuttlites.h
中的方法时,
/
会从协议中剥离,因此这是明显的缺陷。我能想出的最接近我发布的原始解决方案是:

[@[ @"http://example.com", @"foo", @"bar" ] componentsJoinedByString:@"/"]
您只需要为路径分隔符使用一个文本,它是什么

NSString
通常以“/”作为路径分隔符表示路径 和“.”作为扩展分隔符


我刚刚遇到了stringByAppendingPathComponent的一个问题:它到处都会删除双斜杠!:

NSString* string1 = [[self baseURL] stringByAppendingString:partial];
NSString* string2 =  [[self baseURL] stringByAppendingPathComponent:partial];

NSLog(@"string1 is %s", [string1 UTF8String]);
NSLog(@"string2 is %s", [string2 UTF8String]);
对于baseURl

和一部分/更多

生成两个字符串:

2012-09-07 14:02:09.724 myapp string1正在运行

2012-09-07 14:02:09.749 myapp string2是https:/blah.com/moreblah

但出于某种原因,我打电话到blah.com,用单斜杠来获取资源。但它向我指出,stringByAppendingPathComponent用于路径,而不是URL

这是在运行iOS 5.1的iPhone4硬件上实现的

我输出UTF8字符串,因为我想确保我看到的调试器输出是可信的


所以我想我是说-不要在URL上使用路径,使用一些自制软件或库。

当您使用URL时,您应该使用
NSURL
方法:

NSURL * url = [NSURL URLWithString: @"http://example.com"];
url = [[url URLByAppendingPathComponent:@"foo"] URLByAppendingPathComponent:@"bar"]

还是迅速


stringByAppendingPathComponent
理论上将使用“系统路径分隔符”而不是硬连接到您的格式中的路径分隔符,使您的代码(稍微)独立于系统。但当然,Objective-C在Windoze上并不常用,所以这不是什么大问题。我从URL中剥离//得到的结果是:输出为http:/example.com/foo/bar,这很糟糕。请参见下文。双斜杠被减少为单斜杠可能是path方法调用的结果,因此它不适用于URL。顺便说一句,我在回复您后立即更新了我的答案。这可能是新的行为(在过去一年左右)-我认为带有“//”和“…”的路径可用于恶意活动(例如尝试在文件系统中“不同”的地方)。
NSURL * url = [NSURL URLWithString: @"http://example.com"];
url = [[url URLByAppendingPathComponent:@"foo"] URLByAppendingPathComponent:@"bar"]
var url = NSURL.URLWithString("http://example.com")
url = url.URLByAppendingPathComponent("foo").URLByAppendingPathComponent(".bar")