Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Build a list of constants variable from other constants

I've just read all of objective-c global constants variables Q&A but I found them inappropriate to my problem.

I need a list of variable like this:

NSString *baseURL = @"http://example.org";
NSString *mediaURL = @"http://example.org/media/";
NSString *loginURL = @"http://example.org/login/";
NSString *postURL = @"http://example.org/post/";
etc.

Of course I can't use this code because it's a very bad approach and if I need to change the base url I must change all variables. Since I need these variables to be accessed from every class of the app I declared them as global with this approach:

// Constants.h
extern NSString *const baseURL;
extern NSString *const mediaURL;
extern NSString *const loginURL;
extern NSString *const postURL;


// Constants.m
NSString *const baseURL = @"http://example.org";
NSString *const mediaURL = [NSString stringWithFormat:"%@%@", baseURL, @"/media/"];
NSString *const loginURL = [NSString stringWithFormat:"%@%@", baseURL, @"/login/"];
NSString *const postURL = [NSString stringWithFormat:"%@%@", baseURL, @"/post/"];

BUT I can't do this because I get this error:

Initializer element is not a compile-time constant

This happens because objects works at runtime.

Now my question is, once and for all I hope, what is a nice and good way to handle this pretty usual scenario in network apps?

I think use a class (or a singleton class) for handle the constants variables is a bit overkill, and it's also too verbose use something like [MyClass globalVar] every time I need it.

Ideas about it?

like image 655
Fred Collins Avatar asked Apr 07 '12 14:04

Fred Collins


2 Answers

#define API_ROOT_URL @"https://www.example.org/api"
NSString *const OAuthUrl = API_ROOT_URL @"/oauthToken";

See also.

like image 28
sanmai Avatar answered Sep 22 '22 13:09

sanmai


I know it's old-fashioned but I'd just use preprocessor macros and let constant string concatenation handle it.

#define baseURL @"http://example.org"
#define mediaURL baseURL@"/media/"
like image 145
Phillip Mills Avatar answered Sep 23 '22 13:09

Phillip Mills