Norbert Norbert - 3 months ago 5x
Objective-C Question

Nested #defines to build a URL?

I want to have some URLs as hardcoded

s. Some of them require usernames. I am looking for the possibility to do the following:

#define kUserName John
#define kUserInfoURL(USERNAME) [NSURL URLWithString:@""]

Can this be done?


It can be done, it's called stringification (see link):

#define kUserInfoURL(USERNAME) [NSURL URLWithString:@"" #USERNAME]

However, this is gonna work with hardcoded usernames only. If you pass a variable, you'll get the name of the variable, not its contents. Why don't you create a method or function which will return you the same?


#define kBaseUrl @""

- (NSURL*)createUrlForUser:(NSString*)username {
   NSString* url = [NSString stringWithFormat:@"%@/%@", kBaseUrl, username];
   return [NSURL URLWithString:url];