Create a list of variable constants from other constants

I just read all the objective-c variables of the global Q & A constants , but I found them unacceptable for my problem.

I need a list of variables:

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 cannot use this code because it is a very bad approach, and if I need to change the base url, I have to change all the variables. Since I need these variables to access from each application class, I declared them global using 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 cannot do this because I get this error:

 Initializer element is not a compile-time constant 

This is because objects work at runtime.

Now, to my question, once and for all I hope that this is a good and good way to handle this fairly common scenario in network applications?

I think using a class (or a singleton class) to handle variable constants is a little redundant, and it also uses too much verbose something like [MyClass globalVar] every time I need it.

Ideas about it?

+5
source share
3 answers

I know this is old fashioned, but I just use preprocessor macros and let the constant string concatenate to handle it.

 #define baseURL @"http://example.org" #define mediaURL baseURL@ "/media/" 
+4
source
 #define API_ROOT_URL @"https://www.example.org/api" NSString *const OAuthUrl = API_ROOT_URL @"/oauthToken"; 

See also.

+2
source

I donโ€™t have access to MAC now ... can you just try this.

in .h

 NSString *baseURLString; extern NSString *const baseURL; 

in .m

 baseURLString= @"http://example.org"; NSString *const baseURL= [NSString stringWithFormat:"%@", baseURL]; 

I'm not sure if this will work.

And also you saw this answer in SO ... it has all the approaches that I know about ... Constants in Objective-C

0
source

Source: https://habr.com/ru/post/945020/


All Articles