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?
#define API_ROOT_URL @"https://www.example.org/api"
NSString *const OAuthUrl = API_ROOT_URL @"/oauthToken";
See also.
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/"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With