0

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" ?

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
Pierre de LESPINAY
  • 44,700
  • 57
  • 210
  • 307
  • 1
    What about generating string within a loop, and converting it into NSURL ? – Anoop Vaidya Jan 23 '13 at 11:30
  • This url is a public member of a class that I use in several different location. You are saying I have to recreate the NSURL each time I need it ? – Pierre de LESPINAY Jan 23 '13 at 11:37
  • Yes, something like this NSString *str=[NSString stringwithFormat:@"%@%d",url,counter], and then convert it into url as NSURL *finalURL = [NSURL URLWithString:str]; – Anoop Vaidya Jan 23 '13 at 11:39

2 Answers2

4

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]]];
Community
  • 1
  • 1
WDUK
  • 18,870
  • 3
  • 64
  • 72
1

You should make the base URL as you're doing and then build the others relative to it using +[NSURL URLWithString:relativeToURL:].

Ken Thomases
  • 88,520
  • 7
  • 116
  • 154
  • This would bring the maintainability but I still have to do `[[NSURL alloc] initWithString: my_path relativeToURL: url].absoluteString` each time I need to get the new url string, don't I ? – Pierre de LESPINAY Jan 23 '13 at 12:24
  • If you need a string from it, yes, you have to ask it for a string. – Ken Thomases Jan 23 '13 at 18:03