Ming Leung
Ming Leung

Reputation:

How to reference an environment variable inside Obj-C code

I define a path variable in Xcode source tree called "MY_SRC_DIR". I would like to get the value of this environment variable and put it in a NSString in the obj-c code. For example,

-(NSString*) getSourceDir

{

    return @"${MY_SRC_DIR}"; // not the right solution and this is the question

}

Upvotes: 41

Views: 26915

Answers (5)

David H.
David H.

Reputation: 2862

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!! :]

Upvotes: 31

William Jockusch
William Jockusch

Reputation: 27295

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 defined
MACRO_FIRST_PRESIDENT is Washington, George

Upvotes: 14

geowar
geowar

Reputation: 4447

The only way I've found to get a build time environment variable as a string is to put it in an dictionary element like this:

<key>Product Name</key>
<string>$PRODUCT_NAME</string>

and then retrieve it like this:

NSDictionary* infoDict = [[NSBundle mainBundle] infoDictionary];
NSString* productName = infoDict[@"Product Name"];
NSLog(@"Product Name: %@", productName);

Upvotes: 8

bobwaycott
bobwaycott

Reputation: 524

The best answer to this question is the accepted answer on this question.

Constants in Objective-C

You'll get the most mileage, and won't need any special methods to get the value you're searching for as long as you import the file into whatever .h/.m file is going to consume said value.

Upvotes: -4

highlycaffeinated
highlycaffeinated

Reputation: 19867

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"]

Upvotes: 67

Related Questions