- [NSString stringByAppendingPathComponent:] or just - [NSString stringByAppendingFormat:] for NSStrings for NSURL?

When called +[NSURL URLWithString:], I have two options for creating my URLs:

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

or

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

-[NSString stringByAppendingPathComponent:]seems like a more correct answer, but am I losing anything using -[NSString stringByAppendingFormat:], in addition to handling double slashes, as in the following case?

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

// http://example.com//foo/bar  oops!
[@"http://example.com/" stringByAppendingFormat:@"/%@/%@",@"foo",@"bar"];
+5
source share
4 answers

When you work with URLS, you should use methods NSURL:

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

or in Swift

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

I just ran into a problem with stringByAppendingPathComponent: it removes double slashes everywhere !:

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

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

for url base https://blah.com

and partial part / moreblah

Produces two lines:

2012-09-07 14: 02: 09.724 myapp string1 https://blah.com/moreblah

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

- blah.com, . , stringByAppendingPathComponent - URL-.

iPhone 4, iOS 5.1.

UTF8, , , , .

, , - URL-, brew .

+3

:

< >   [NSString pathWithComponents: @[@ "http://example.com", @ "foo", @ "bar" ]] >

, a / NSPathUtitlites.h, . , , , :

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

You just need to use a literal for the path separator, which is NSString.

NSStringrepresents paths in general with '/ as a path separator as well as'. as an extension separator.

+1
source

dot stringByAppendingPathComponent is designed to handle double slashes, however you can do something like:

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

All Articles