【发布时间】:2012-09-06 21:02:55
【问题描述】:
当调用 +[NSURL URLWithString:] 时,我有两个选项来构建我的 URL:
[[@"http://example.com" stringByAppendingPathComponent:@"foo"] stringByAppendingPathComponent:@"bar"]
或
[@"http://example.com" stringByAppendingFormat:@"/%@/%@",@"foo",@"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理论上将使用“系统路径分隔符”与硬连接到您的格式中的路径分隔符,使您的代码(稍微更多)与系统无关。当然,Objective-C 在 Windoze 上不是很常用,所以这不是什么大问题。