Norbert Norbert - 1 year ago 89
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?

Answer Source

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];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download