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*) getSourc开发者_JS百科eDir
{
return @"${MY_SRC_DIR}"; // not the right solution and this is the question
}
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.
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 defined
MACRO_FIRST_PRESIDENT is Washington, George
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);
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.
精彩评论