Reputation:
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
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.
Hope it helps!! :]
Upvotes: 31
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
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
Reputation: 524
The best answer to this question is the accepted answer on this question.
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
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