Search code examples
iosnsurl

NSURL - Set modify path


I need to use a NSURL object to reach different ressources on the same host.

Here is what I do:

#define MY_HOST @"my.server.eu"
NSURL *url = [[NSURL alloc] initWithScheme:@"http" host:MY_HOST path:@"/"];

Now I need to deal with

How can I modify the path of my NSURL object ?
Why can't we simply do url.path = @"path1" ?


Solution

  • How can I modify the path of my NSURL object ?

    Why can't we simply do url.path = @"path1" ?

    Because NSURL is an immutable object, and you can't change its properties afterwards. NSMutableURL does not exist, but is on the wish list of many.

    In order to achieve what you're after, you're going to have to make 3 separate NSURL objects I'm afraid. To do so, you can convenience the paths within an array:

    NSString *host = @"http://my.server.eu/";
    NSArray *paths = @[@"path1", @"path2", @"path3"];
    
    NSURL *path1 = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", host, path[0]]];
    NSURL *path2 = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", host, path[1]]];
    NSURL *path3 = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", host, path[2]]];