How to reference an environment variable inside Obj-C code How to reference an environment variable inside Obj-C code xcode xcode

How to reference an environment variable inside Obj-C code


From http://rosettacode.org/wiki/Environment_variables#Objective-C:

[[NSProcessInfo processInfo] environment] returns an NSDictionary of the current environment.

For example:

[[[NSProcessInfo processInfo] environment] objectForKey:@"MY_SRC_DIR"]


Just expose the desired var into the Environment Variables list of your current Xcode's deployment Scheme and you'll be able to retrieve it at runtime like this:

NSString *buildConfiguration = [[NSProcessInfo processInfo] environment][@"BUILD_CONFIGURATION"];

It also applies to swift based projects.

Adding Xcode Build Setting Var to Environment var

Hope it helps!! :]


Here is another way to do it:

.xcconfig file:

FIRST_PRESIDENT = '@"Washington, George"'GCC_PREPROCESSOR_DEFINITIONS = MACRO_FIRST_PRESIDENT=$(FIRST_PRESIDENT)

objective C code:

#ifdef FIRST_PRESIDENT    NSLog(@"FIRST_PRESIDENT is defined");#else    NSLog(@"FIRST_PRESIDENT is NOT defined");#endif#ifdef MACRO_FIRST_PRESIDENT    NSLog(@"MACRO_FIRST_PRESIDENT is %@", MACRO_FIRST_PRESIDENT);#else    NSLog(@"MACRO_FIRST_PRESIDENT is undefined, sorry!");#endif

Console output -- I've stripped out the garbage from NSLog:

FIRST_PRESIDENT is NOT definedMACRO_FIRST_PRESIDENT is Washington, George