gpt4 book ai didi

objective-c - -[NSString stringByAppendingPathComponent :] or just -[NSString stringByAppendingFormat:] for NSStrings for NSURLs?

转载 作者:太空狗 更新时间:2023-10-30 03:50:38 29 4
gpt4 key购买 nike

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

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

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

-[NSString stringByAppendingPathComponent:] 似乎是更正确的答案,但是除了像以下案例?

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

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

最佳答案

当你使用 URLS 时,你应该使用 NSURL 方法:

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

或在 Swift 中

var url = NSURL.URLWithString("http://example.com")
url = url.URLByAppendingPathComponent("foo").URLByAppendingPathComponent(".bar")

关于objective-c - -[NSString stringByAppendingPathComponent :] or just -[NSString stringByAppendingFormat:] for NSStrings for NSURLs?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12308347/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com