Reputation: 4975
Fellow Coders...
Constants.h
extern NSString * const LOGIN_URL;
Constants.m
NSString * const LOGIN_URL = @"http://www.url.com";
Anyway I can replicate the following psuedo code below into Objective C?
if([[[[NSBundle mainBundle] infoDictionary] objectForKey:@"DebugMode"] boolValue] == NO)
{
NSString * const LOGIN_URL = @"http://www.production-url.com";
}
else
{
NSString * const LOGIN_URL = @"http://www.qa-url.com";
}
Upvotes: 0
Views: 2901
Reputation: 4558
Whenever I've had a situation like this I've just created a class method in my constants file:
+ (NSString *)loginURL {
if([[[[NSBundle mainBundle] infoDictionary] objectForKey:@"DebugMode"] boolValue] == NO){
return @"http://www.production-url.com";
}
else {
return @"http://www.qa-url.com";
}
}
It also makes it more clear in your code that as the loginURL
string is coming via a method, it may be dependent on a run time condition:
NSURL *loginURL = [NSURL URLWithString:[Constants loginURL]];
Upvotes: 1
Reputation: 440
What your asking for isn't exactly possible (at least not in the way your asking for). A constant is setup and established whilst compiling (not strictly true, but for the sake of this explanation, it will do) and thus means that it can not be mutated for any reason at runtime.
The traditional way of changing the values of constants depending on debug and release code is through the preprocessor. Like so:
#if __DEBUG_MODE__ == 1
NSString * const LOGIN_URL = @"http://www.qa-url.com";
#else
NSString * const LOGIN_URL = @"http://www.production-url.com";
#endif
Now __DEBUG_MODE__
needs to be defined before it can do anything, and there are a few ways you could do this. You could add the following line to you prefix header file (.pch)
#define __DEBUG_MODE__ 1 // Change to 0 to disable debug mode.
or add the compiler flag -M__DEBUG_MODE__=1
to the file you wish to effect. This means that whenever __DEBUG_MODE__
is set with a value of 1, the compiler will use your debug constant, and when it has a value of 0 the compiler will use the production constant.
This also has the benefit of keeping debug and production code separate (you should avoid having both in your binary as it can open a whole world of problems and security issues).
Hope this helps.
Upvotes: 4